//鏈式隊列的存儲 //楊鑫 #include#include typedef int QElemType; //定義節點 typedef struct QNode { QElemType data; struct QNode *next; }QNode, *QueuePtr; //定義指針 typedef struct { QueuePtr front; QueuePtr rear; }LinkQueue; //插入元素e進入隊列 void en_Queue(LinkQueue *q, QElemType e) { QueuePtr temp = (QueuePtr)malloc(sizeof(QNode)); if(temp) { temp->data = e; temp->next = NULL; q->rear->next = temp; q->rear = temp; } } //初始化隊列 void init_Queue(LinkQueue *q) { q->front = q->rear = (QNode *)malloc(sizeof(QNode)); q->front->next = NULL; } //創建隊列 void create_Queue(LinkQueue *q) { int n = 0; init_Queue(q); printf("請輸入要進入隊列的元素,以0結束!\n"); while(scanf("%d", &n)) { if(n == 0) break; en_Queue(q, n); } } //e元素出隊 void de_Queue(LinkQueue *q, QElemType *e) { if(q->front == q->rear) return; QueuePtr temp = q->front->next; if(q->front->next == q->rear) q->rear = q->front; *e = temp->data; q->front->next = temp->next; free(temp); } //判斷隊列是否為空 int is_Empty(LinkQueue *q) { if(q->front == q->rear) return 1; return 0; } //返回隊列 int getlength_Queue(LinkQueue *q) { QueuePtr temp = q->front; int i = 0; while(temp != q->rear) { ++i; temp = temp->next; } return i; } //清空隊列 void clear(LinkQueue *q) { QueuePtr temp = q->front->next; while(temp) { QueuePtr tp = temp; temp = temp->next; free(tp); } temp = q->front; q->front = q->rear = NULL; free(temp); } //打印隊列元素 void print_Queue(LinkQueue *q) { if(q->front == q->rear) return; QueuePtr temp = q->front->next; while(temp != q->rear) { printf("%d ", temp->data); temp = temp->next; } printf("%d", temp->data); printf("\n"); } //第一個數據出隊 void top_Queue(LinkQueue *q, QElemType *e) { if(q->front == q->rear) return; *e = q->front->next->data; } int main() { int i = 0, k = 0, top = 0; int len; LinkQueue q; create_Queue(&q); top_Queue(&q, &top); printf("隊頭的元素為:%d\n", top); len = getlength_Queue(&q); printf("遍歷隊中的所有元素:\n"); for(i = 0; i < len; i++) { de_Queue(&q, &k); printf("%d ", k); } printf("\n"); clear(&q); return 0; }