算法导论chapter10队列的实现
代码奉上,原理灰常简单:
#include<iostream> using namespace std; const int MAX = 1000; struct my_queue { int data[MAX]; int head, tail; }; my_queue Init() { my_queue queue; queue.head = queue.tail=0; return queue; } bool empty(my_queue q) { return q.head == q.tail; } void enqueue(my_queue &q, int value) { if(q.head == q.tail+1) { cerr << "Queue flow\n"; exit(1); } q.data[q.tail] = value; q.tail = (q.tail + 1) % MAX; } int dequeue(my_queue &q) { if(empty(q)) { cerr << "The queue is empty!\n" ; exit(1); } int x = q.data[q.head]; q.head = (q.head + 1) % MAX; return x; } int main() { my_queue q = Init(); enqueue(q,10); cout << dequeue(q)<<endl; }