链队列
Created|Updated
|Post Views:
前言
链队列就是限制了只能在首端和尾端进行插入,删除操作的表。
1 2 3 4 5 6 7 8 9 10
| typedef struct QNode { ElementType data; struct QNode *next; }QNode, *QNodePtr;
typedef struct ListQueue { QNodePtr front, rear; }ListQueue, *ListQueuePtr;
|
- 空队列判断条件 front和rear同时指向头节点

操作
插入
1 2 3 4 5 6 7 8 9 10 11 12 13
| void EnQueue(ListQueuePtr Q, ElementType e) { QNodePtr P = (QNodePtr)malloc(sizeof(QNode)); if(P == NULL) { fprintf(stderr, "Out of space."); exit(1); } P->data = e; P->next = NULL; Q->rear->next = P; Q->rear = P; }
|
删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| void DeQueue(ListQueuePtr Q, ElementType *e) { QNodePtr P; if(Q->front == Q->rear) { fprintf(stderr, "The queue is empty."); exit(1); } P = Q->front->next; *e = P->data; Q->front->next = P->next; if(Q->rear == P) Q->rear = Q->front; free(P); }
|
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #ifndef _l_queue_h_
typedef int ElementType;
typedef struct QNode { ElementType data; struct QNode *next; }QNode, *QNodePtr;
typedef struct ListQueue { QNodePtr front, rear; }ListQueue, *ListQueuePtr;
void InitQueue(ListQueuePtr Q);
void EnQueue(ListQueuePtr Q, ElementType e);
void DeQueue(ListQueuePtr Q, ElementType *e);
void Traverse(ListQueuePtr Q); #endif
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include<stdio.h> #include<stdlib.h> #include "l_queue.h"
void InitQueue(ListQueue *Q) { Q->front = Q->rear = (QNodePtr)malloc(sizeof(QNode)); if(Q->front == NULL) { fprintf(stderr, "Out of space."); exit(1); } Q->front->next = NULL; }
void EnQueue(ListQueuePtr Q, ElementType e) { QNodePtr P = (QNodePtr)malloc(sizeof(QNode)); if(P == NULL) { fprintf(stderr, "Out of space."); exit(1); } P->data = e; P->next = NULL; Q->rear->next = P; Q->rear = P; }
void DeQueue(ListQueuePtr Q, ElementType *e) { QNodePtr P; if(Q->front == Q->rear) { fprintf(stderr, "The queue is empty."); exit(1); } P = Q->front->next; *e = P->data; Q->front->next = P->next; if(Q->rear == P) Q->rear = Q->front; free(P); }
void Traverse(ListQueuePtr Q) { QNodePtr P = (QNodePtr)malloc(sizeof(QNode)); P = Q->front->next; while (P != NULL) { printf("%d ", P->data); P = P->next; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include<stdio.h> #include<stdlib.h> #include "l_queue.h"
int main() { ListQueue Q; InitQueue(&Q); for(int i = 0; i < 4; i++) { EnQueue(&Q, i); } int *e; DeQueue(&Q, e); Traverse(&Q); }
|