使用链表实现队列操作

编程入门 行业动态 更新时间:2024-10-23 06:22:27

使用链表实现<a href=https://www.elefans.com/category/jswz/34/1771257.html style=队列操作"/>

使用链表实现队列操作

代码如下:

#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 
 

更多推荐

使用链表实现队列操作

本文发布于:2023-12-03 20:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1657267.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:队列   链表   操作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!