C++|C++ 数据结构与算法 栈,队列,链式队列,循环队列

class ArrayStack { private: int *data; int num; int len; public: ArrayStack(int n) { data = https://www.it610.com/article/new int[n]; num = 0; len = n; }bool push(int item) { if(num == len) { return false; } else{ data[num] = item; num++; return true; } }int pop() { if(num == 0) { return -1; } else { int item = data[num-1]; num--; return item; } } }

  1. 队列
class ArrayQueue { private: int *data; int head; int tail; int len; public: ArrayQueue(int n) { data = https://www.it610.com/article/new int[n]; head = 0; tail = 0; len = n; }bool enqueue(int item) { if(tail == len && head == 0) { cout <<"queue is full" << endl; return false; } else { if(tail == len && head != 0) { int num = tail - head; for(int i = 0 ; i < num ; i++) { data[i] = data[len - num + i]; } } data[tail] = item; tail++; return true; } }int dequeue() { if(head == tail) { cout << "queue is empty" << endl; return -1; } else { int item = data[head]; head++; return item; } } }

  1. 链式队列
struct linked_list { int data; linked_list *next; }; class ListQueue { private: linked_list *head; linked_list *tail; int num; public: ListQueue() { head = new linked_list; head->data = https://www.it610.com/article/-1; head->next = NULL; tail = head; num = 0; }bool enQueue(int item) { linked_list *node = new linked_list; if(node) { node->data = https://www.it610.com/article/item; node->next = NULL; tail->next = node; tail = node; num++; return true; } else { return false; } }int deQueue() { if(head == tail) { return -1; } else { if(head->next == tail) { tail = head; }int item = head->next->data; num--; linked_list *node = head->next; head->next = node->next; delete node; return item; } } }

【C++|C++ 数据结构与算法 栈,队列,链式队列,循环队列】4 . 循环队列
class CircularQueue { private: int *data; int head; int tail; int len; public: CircularQueue(int n) { data = https://www.it610.com/article/new int[n]; head = 0; tail = 0; len = n; }bool enQueue(int item) { if((tail+1)%len == head) { return false; } else { data[tail] = item; tail++; if(tail == len) { tail = 0; } return true; } }int deQueue() { if(head == tail) { return -1; } else { int item = data[head]; head++; if(head == len) { head = 0; }return item; } }void print() { cout << head <<" " << tail << endl; } }

    推荐阅读