1. 程式人生 > >隊列的定義與操作——順序存儲和鏈式存儲

隊列的定義與操作——順序存儲和鏈式存儲

順序存儲 type void == int isf sem urn ont

  隊列的 存儲結構順序存儲 鏈式存儲

  1. 隊列的順序存儲與操作 (循環隊列)

 1 typedef int Position;
 2 struct QNode {
 3     ElementType *Data;     // 存儲元素的數組 
 4     Position Front, Rear;  // 隊列的 頭、尾指針 
 5     int Cap;               // 隊列最大大容量 
 6 };
 7 typedef struct QNode *Queue; 
 8 
 9 // 操作集
10 Queue CreateQueue(int MaxSize);
11 int IsFull(Queue Q); 12 int IsEmpty(Queue Q); 13 void AddQ(Queue Q, ElementType X); 14 ElementType DeleteQ(Queue Q); 15 16 Queue CreateQueue() 17 { 18 Queue Q = (Queue)malloc(sizeof(struct QNode)); 19 Q->Data = (ElementType*)malloc(MaxSize * sizeof(ElementType)); 20 Q->Front = Q->Rear = 0
; 21 Q->Cap= MaxSize; 22 23 return Q; 24 } 25 26 int IsFull(Queue Q) 27 { 28 return (Q->Rear+1)%Q->MaxSize == Q->Front; 29 } 30 31 void AddQ(Queue Q, ElementType X) 32 { 33 if ( IsFull(Q) ) 34 return; // queue is fulled 35 else { 36 Q->Rear = (Q->Rear+1
)%Q->MaxSize; 37 Q->Data[Q->Rear] = X; 38 } 39 } 40 41 int IsEmpty(Queue Q) 42 { 43 return (Q->Front == Q->Rear); 44 } 45 46 ElementType DeleteQ(Queue Q) 47 { 48 if ( IsEmpty(Q) ) 49 return NULL; // 這裏的返回值應該視具體情況而定(可能返回 NULL,或者返回 ElementType 類型) 50 else { 51 Q->Front = (Q->Front+1)%Q->MaxSize; 52 return Q->Data[Q->Front]; 53 } 54 }

  2.隊列的鏈式存儲與操作

 1 typedef struct Node *PtrToNode;
 2 struct Node {    // 隊列中的節點 
 3     ElementType Data;
 4     PtrToNode Next;
 5 };
 6 typedef PtrToNode Position;
 7 
 8 struct QNode {
 9     Position Front, Rear;    // 隊列的頭、尾指針 
10 };
11 typedef struct QNode *Queue;
12 
13 // 操作集
14 Queue CreateQueue();
15 int IsEmpty(Queue Q);
16 void AddQ(Queue Q, ElementType X);
17 ElementType DeleteQ(Queue Q);
18 
19 Queue CreateQueue()
20 {
21     Queue Q = (Queue)malloc(sizeof(struct QNode));
22     Q->Front = Q->Rear = NULL;
23     
24     return Q;
25 }
26 
27 int IsEmpty(Queue Q)
28 {
29     return ( Q->Front == NULL );
30 }
31 
32 void AddQ(Queue Q, ElementType X)
33 {
34     PtrToNode TmpCell = (struct Node*)malloc(sizeof(struct Node)); 
35     TmpCell->Next = NULL;
36     TmpCell->Data= X;
37     
38     if ( IsEmpty(Q) )    //  隊列為空 
39         Q->Front = Q->Rear = TmpCell;
40     else {
41         Q->Rear->Next = TmpCell;
42         Q->Rear = TmpCell;
43     }
44 }
45 
46 ElementType DeleteQ(Queue Q)
47 {
48     if ( IsEmpty(Q) )    return NULL;  // 這裏的返回值應該視具體情況而定(可能返回 NULL,或者返回 ElementType 類型)
49     
50     Position FrontCell;
51     ElementType FrontElem;
52     FrontCell = Q->Front;
53     
54     if ( Q->Front == Q->Rear )        //  若隊列中只有一個元素 
55         Q->Front = Q->Rear = NULL;    //  刪除後置空 
56     else                         
57         Q->Front = Q->Front->Next;
58     
59     FrontElem = FrontCell->Data;
60     free(FrontCell);
61     
62     return FrontElem;
63 }

隊列的定義與操作——順序存儲和鏈式存儲