1. 引言
为 了便于插入元素,设立了队尾指针。这样插入元素的操作与队列长度无关。本文主要讲解链队列。和栈一样,队列也是操作受限的线性表,只允许在队尾插入元素,在对头删除元素。对于链队列结构,
2. 链队列
#include "ds.h" typedef int QElemType; typedef struct QNode{ QElemType data; struct QNode *next; }*QueuePtr; struct LinkQueue{ QueuePtr front, rear; }; void InitQueue(LinkQueue &Q); void DestroyQueue(LinkQueue &Q); void ClearQueue(LinkQueue &Q); Status QueueEmpty(LinkQueue Q); int QueueLength(LinkQueue Q); Status GetHead(LinkQueue Q, QElemType &e); void EnQueue(LinkQueue &Q, QElemType e); Status DeQueue(LinkQueue &Q, QElemType &e); void QueueTraverse(LinkQueue Q, void(*vi)(QElemType)); // 带头结点的单链队列 void InitQueue(LinkQueue &Q) { Q.front = (QueuePtr)malloc(sizeof(QNode)); if (!Q.front) exit(OVERFLOW); Q.front->next = NULL; Q.rear = Q.front; } void DestroyQueue(LinkQueue &Q) { QueuePtr q, p = Q.front; while (p) { q = p->next; free(p); p = q; } Q.front = Q.rear = NULL; } void ClearQueue(LinkQueue &Q) { QueuePtr q, p = Q.front->next; while (p) { q = p->next; free(p); p = q; } Q.front->next = NULL; Q.rear = Q.front; } Status QueueEmpty(LinkQueue Q) { if (Q.front == Q.rear) return TRUE; else return FALSE; } int QueueLength(LinkQueue Q) { int i = 0; QueuePtr p = Q.front->next; while (p) { i++; p = p->next; } return i; } Status GetHead(LinkQueue Q, QElemType &e) { if (Q.front->next) { memcpy(&e, &(Q.front->next->data), sizeof(QElemType)); return OK; } else { return FALSE; } } void EnQueue(LinkQueue &Q, QElemType e) { QueuePtr p = (QueuePtr)malloc(sizeof(QNode)); if (!p) exit(OVERFLOW); p->next = NULL; memcpy(&(p->data), &e, sizeof(QElemType)); Q.rear->next = p; Q.rear = p; } Status DeQueue(LinkQueue &Q, QElemType &e) { QueuePtr p = Q.front, q; if (Q.front == Q.rear) return FALSE; q = p->next; memcpy(&e, &(q->data), sizeof(QElemType)); p->next = q->next; if (Q.rear == q) Q.rear = Q.front; free(q); return OK; } void QueueTraverse(LinkQueue Q, void(*vi)(QElemType)) { QueuePtr p = Q.front->next; while (p) { vi(p->data); p = p->next; } printf("\n"); } void print(QElemType e) { printf("%d ", e); } int main() { int i; QElemType d; LinkQueue q; InitQueue(q); printf("成功地构造了一个空队列!\n"); printf("是否空队列?%d(1:空 0:否) ",QueueEmpty(q)); printf("队列的长度为%d\n",QueueLength(q)); EnQueue(q,-5); EnQueue(q,5); EnQueue(q,10); printf("插入3个元素(-5,5,10)后,队列的长度为%d\n",QueueLength(q)); printf("是否空队列?%d(1:空 0:否) ",QueueEmpty(q)); printf("队列的元素依次为:"); QueueTraverse(q,print); i=GetHead(q,d); if(i==OK) printf("队头元素是:%d\n",d); DeQueue(q,d); printf("删除了队头元素%d\n",d); i=GetHead(q,d); if(i==OK) printf("新的队头元素是:%d\n",d); ClearQueue(q); printf("清空队列后,q.front=%u q.rear=%u q.front->next=%u\n",q.front,q.rear,q.front->next); DestroyQueue(q); printf("销毁队列后,q.front=%u q.rear=%u\n",q.front, q.rear); }