スタックとキューを配列をC++で実装してみました
キューは頑張って循環キューにしました。
StackClass
class Stack {
typedef int element_type;
private:
static int MAX_LENGTH;
element_type* data;
int head;
public:
Stack() {
this->data = new int[MAX_LENGTH];
this->head = 0;
}
element_type pop() {
if (this->head == 0) {
printf("Stack Underflow");
exit(1);
}
this->head--;
return this->data[this->head];
}
void push(element_type value) {
if (this->head == this->MAX_LENGTH) {
printf("Stack Overflow");
exit(1);
}
this->data[this->head] = value;
this->head ++;
return;
}
};
int Stack::MAX_LENGTH = 128;
QueueClass
class Queue {
typedef int element_type;
private:
static int MAX_LENGTH;
element_type* data;
int head, tail;
public:
Queue() {
this->data = new int[MAX_LENGTH];
this->head = 0;
this->tail = 0;
}
element_type dequeue() {
if (this->tail == this->head) {
printf("Empty");
exit(1);
}
element_type value = this->data[this->head];
this->head++;
if (this->head == this->MAX_LENGTH) {
this->head = 0;
}
return value;
}
void enqueue(element_type value) {
prev_tail = this->tail;
this->tail++;
if (this->tail == this->MAX_LENGTH) {
this->tail = 0
}
if (this->tail == this->head) {
printf("Overflow");
exit(1);
}
this->data[prev_tail] = value;
return;
}
};
int Stack::MAX_LENGTH = 128;
キューは頑張って循環キューにしたのですが、配列でキューやる時って、キューいっぱいの状態って、1データ分余っちゃうのしょうがないんでしたっけ??そんな風に昔授業で言っていた気がする。
次はリンクドリストで実装してみたいと思います。