已解决
使用链表实现队列操作
来自网友在路上 143843提问 提问时间:2023-10-25 04:01:09阅读次数: 43
最佳答案 问答题库438位专家为你答疑解惑
代码如下:
#include <stdio.h>
#include <stdlib.h>
#define NULL 0struct node
{int data;struct node *next;
};struct queue
{struct node *front, *rear;
};struct queue q;/*初始化队列首尾节点均为NULL*/
void createqueue() { q.front = q.rear = NULL; }int empty()
{if (q.front == NULL)return 1;elsereturn 0;
}/*插入节点*/
void insert(int x)
{struct node *pnode;pnode = (struct node *)malloc(sizeof(struct node));if (pnode == NULL){printf("Memory overflow. Unable to insert.\n");exit(1);}pnode->data = x;pnode->next = NULL; /*新节点是最后一个节点*/if (empty())q.front = q.rear = pnode;else{(q.rear)->next = pnode;q.rear = pnode;}
}/*删除节点*/
int removes()
{int x;struct node *p;if (empty()){printf("Queue Underflow. Unable to remove.\n");exit(1);}p = q.front;x = (q.front)->data;q.front = (q.front)->next;if (q.front == NULL) q.rear = NULL;free(p);return x;
}/*显示节点*/
void show()
{struct node *p;if (empty())printf("Queue empty. No data to display \n");else{printf("Queue from front to rear is as shown: \n");p = q.front;while (p != NULL){printf("%d ", p->data);p = p->next;}printf("\n");}
}/*销毁队列*/
void destroyqueue() { q.front = q.rear = NULL; }int main()
{int x, ch;createqueue();do{printf("\n\n Menu: \n");printf("1:Insert \n");printf("2:Remove \n");printf("3:exit \n");printf("Enter your choice: ");scanf("%d", &ch);switch (ch){case 1:printf("Enter element to be inserted: ");scanf("%d", &x);insert(x);show();break;case 2:x = removes();printf("Element removed is: %d\n", x);show();break;case 3:break;}} while (ch != 3);destroyqueue();return 0;
}
运行结果:
Menu:
1:Insert
2:Remove
3:exit
Enter your choice: 1
Enter element to be inserted: 99
Queue from front to rear is as shown:
99
Menu:
1:Insert
2:Remove
3:exit
Enter your choice: 1
Enter element to be inserted: 88
Queue from front to rear is as shown:
99 88
Menu:
1:Insert
2:Remove
3:exit
Enter your choice: 1
Enter element to be inserted: 11
Queue from front to rear is as shown:
99 88 11
Menu:
1:Insert
2:Remove
3:exit
Enter your choice: 2
Element removed is: 99
Queue from front to rear is as shown:
88 11
查看全文
99%的人还看了
相似问题
- 〖大前端 - 基础入门三大核心之JS篇㊲〗- DOM改变元素节点的css样式、HTML属性
- Java 算法篇-链表的经典算法:判断回文链表、判断环链表与寻找环入口节点(“龟兔赛跑“算法实现)
- 代码随想录二刷 | 链表 | 删除链表的倒数第N个节点
- 节点导纳矩阵
- bhosts 显示节点 “unreach“ 状态
- 电子电器架构 —— 车载网关边缘节点总线转换
- 〖大前端 - 基础入门三大核心之JS篇㊳〗- DOM访问元素节点
- 第四天||24. 两两交换链表中的节点 ● 19.删除链表的倒数第N个节点 ● 面试题 02.07. 链表相交 ● 142.环形链表II
- CS224W5.1——消息传递和节点分类
- Vue报错解决Error in v-on handler: “Error: 无效的节点选择器:#div1“
猜你感兴趣
版权申明
本文"使用链表实现队列操作":http://eshow365.cn/6-23878-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!