1.概述:
C語言的隊列(queue),是先進先出(FIFO, First-In-First-Out)的線性表數據結構。在具體應用中通常用鏈表或者數組來實現。隊列只允許在后端(稱為rear)進行插入操作,在前端(稱為front)進行刪除操作。
循環隊列可以更簡單的防止偽溢出的發生,但是隊列大小是固定的。
2.實例代碼:
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
/* 隊列的順序存儲結構(循環隊列) */ #define MAX_QSIZE 5 /* 最大隊列長度+1 */ typedef struct { QElemType *base; /* 初始化的動態分配存儲空間 */ int front; /* 頭指針,若隊列不空,指向隊列頭元素 */ int rear; /* 尾指針,若隊列不空,指向隊列尾元素的下一個位置 */ }SqQueue; /* 循環隊列的基本操作(9個) */ void InitQueue(SqQueue *Q) { /* 構造一個空隊列Q */ Q->base= malloc (MAX_QSIZE* sizeof (QElemType)); if (!Q->base) /* 存儲分配失敗 */ exit (OVERFLOW); Q->front=Q->rear=0; } void DestroyQueue(SqQueue *Q) { /* 銷毀隊列Q,Q不再存在 */ if (Q->base) free (Q->base); Q->base=NULL; Q->front=Q->rear=0; } void ClearQueue(SqQueue *Q) { /* 將Q清為空隊列 */ Q->front=Q->rear=0; } Status QueueEmpty(SqQueue Q) { /* 若隊列Q為空隊列,則返回TRUE;否則返回FALSE */ if (Q.front==Q.rear) /* 隊列空的標志 */ return TRUE; else return FALSE; } int QueueLength(SqQueue Q) { /* 返回Q的元素個數,即隊列的長度 */ return (Q.rear-Q.front+MAX_QSIZE)%MAX_QSIZE; } Status GetHead(SqQueue Q,QElemType *e) { /* 若隊列不空,則用e返回Q的隊頭元素,并返回OK;否則返回ERROR */ if (Q.front==Q.rear) /* 隊列空 */ return ERROR; *e=Q.base[Q.front]; return OK; } Status EnQueue(SqQueue *Q,QElemType e) { /* 插入元素e為Q的新的隊尾元素 */ if ((Q->rear+1)%MAX_QSIZE==Q->front) /* 隊列滿 */ return ERROR; Q->base[Q->rear]=e; Q->rear=(Q->rear+1)%MAX_QSIZE; return OK; } Status DeQueue(SqQueue *Q,QElemType *e) { /* 若隊列不空,則刪除Q的隊頭元素,用e返回其值,并返回OK;否則返回ERROR */ if (Q->front==Q->rear) /* 隊列空 */ return ERROR; *e=Q->base[Q->front]; Q->front=(Q->front+1)%MAX_QSIZE; return OK; } void QueueTraverse(SqQueue Q, void (*vi)(QElemType)) { /* 從隊頭到隊尾依次對隊列Q中每個元素調用函數vi() */ int i; i=Q.front; while (i!=Q.rear) { vi(Q.base[i]); i=(i+1)%MAX_QSIZE; } printf ( "\n" ); } |