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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
|
#include <stdio.h> #include <stdlib.h> #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 typedef int ElemType; typedef int Status; typedef struct QueueNode{ ElemType data; struct QueueNode *next; }QueueNode, *QueueNodePtr;
typedef struct{ QueueNodePtr front, rear; }LinkQueue;
Status initQueue(LinkQueue *Q){ Q->front = (QueueNodePtr)malloc(sizeof(QueueNode)); Q->rear = (QueueNodePtr)malloc(sizeof(QueueNode)); if(!Q->front || !Q->rear){ printf("初始化内存分配失败"); return ERROR; } Q->front = Q->rear; Q->front->next = NULL; return OK; }
Status isEmpty(LinkQueue Q){ if(Q.front==Q.rear){ return TRUE; }else{ return FALSE; } }
int getLength(LinkQueue Q){ QueueNodePtr p; p = Q.front->next; int i=0; while(p){ i++; p = p->next; } return i; }
Status enter(LinkQueue *Q, ElemType *e){ QueueNodePtr p = (QueueNodePtr)malloc(sizeof(QueueNode)); if(!p){ printf("新结点内存分配失败,无法入队"); return ERROR; } p->data = e; Q->rear->next = p; Q->rear = p; p->next = NULL; return OK; }
Status leave(LinkQueue *Q, ElemType *e){ if(isEmpty(*Q)){ printf("链队为空,无队元素可出列\n"); return ERROR; } QueueNodePtr p; p = Q->front->next; *e = p->data; Q->front->next = p->next; if(Q->rear == p){ Q->rear = Q->front; } free(p); return OK; }
Status getHead(LinkQueue Q, ElemType *e){ if(isEmpty(Q)){ printf("链队为空,无队头元素\n"); return ERROR; } *e = Q.front->next->data; return OK; }
Status clearQueue(LinkQueue *Q){ QueueNodePtr p, q; p = Q->front->next; Q->rear = Q->front; Q->front->next = NULL; while(p){ q = p; p = p->next; free(q); } return OK; }
Status printQueue(LinkQueue Q){ if(isEmpty(Q)){ printf("当前链队无元素可供打印\n"); return ERROR; } QueueNodePtr p; p = Q.front->next; int i=0; while(p){ i++; printf("从队首至队尾的第%d个元素为:%d\n", i, p->data); p = p->next; } return OK; }
int main(int argc, const char * argv[]) { LinkQueue Q; initQueue(&Q); printf("初始化队列Q后队列的长度为:%d\n此时的链队是否为空?(1是0否):%d\n", getLength(Q), isEmpty(Q)); printf("将1-6按顺序入队后可得链队:\n"); for(int i=1;i<=6;i++){ enter(&Q, i); } printQueue(Q); printf("此时队列的长度为:%d\n", getLength(Q)); int e; getHead(Q, &e); printf("此时队列的队头为:%d\n", e); printf("队列出队两个元素:\n"); leave(&Q, &e); printf("出队:%d\n", e); leave(&Q, &e); printf("出队:%d\n", e); printf("现在的链队为:\n"); printQueue(Q); printf("现在的链队长度为:%d\n", getLength(Q)); getHead(Q, &e); printf("现在链队的队头为:%d\n", e); printf("清空链队后得链队为:\n"); clearQueue(&Q); printQueue(Q); return 0; }
|