队列的基本操作包括入队enqueue和出队dequeue,队列有队头head和队尾tail指针。元素总是从队头出,从队尾入。采用数组实现队列时候,为了合理利用空间,可以采用循环实现队列空间的有效利用。
#include<iostream> using namespace std; struct queue { int *q; int queuesize; int head; int tail; }; void init(queue* q, int n) { q->head = 0; q->tail = 0; q->queuesize = n; q->q = (int*)malloc(sizeof(int)*q->queuesize); } void enqueue(queue* q, int x) { if (((q->tail + 1) % q->queuesize) == q->head) { cout << "queue is full" << endl; } else { q->q[q->tail] = x; q->tail = (q->tail + 1) % q->queuesize; } } int dequeue(queue* q, int *value) { if (q->tail == q->head) return -1; else { *value = q->q[q->head]; q->head = ((q->head++) % q->queuesize); } } int main() { int value; queue q; init(&q, 10); for (int i = 0; i < 9; i++) { enqueue(&q, i + 11); } cout << "head=" << q.head << endl; cout << "tail=" << q.tail << endl; for (int i = 0; i < 9; i++) { if (dequeue(&q, &value) == -1) cout << "queque is empy"<<endl; else printf("value=%d\n", value); } cout << "head=" << q.head << endl; cout << "tail=" << q.tail << endl; return 0; }
时间: 2024-12-06 02:15:06