//链式队列的存储 //杨鑫 #include <stdio.h> #include <stdlib.h> 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; }
时间: 2024-11-08 19:17:05