LoginSignup
0
0

More than 3 years have passed since last update.

「スタックとキュー」 アルゴリズムとデータ構造を復習(1)

Last updated at Posted at 2020-02-20

スタックとキューを配列を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データ分余っちゃうのしょうがないんでしたっけ??そんな風に昔授業で言っていた気がする。
次はリンクドリストで実装してみたいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0