使用 C 语言的链表解释队列
使用链表可以避免队列溢出和队列下溢。
以下是在 C 编程语言中利用链表进行队列操作的步骤 −
- 插入
- 删除
插入
语法如下 −
语法
&item :
Newnode = (node*) mallac (sizeof (node));
newnode ->data = item;
newnode ->link = NULL;
if ((front = = NULL) || (rear = = NULL)){
front= newnode;
rear = newnode;
}else{
Rear->link = newnode;
rear = newnode;
}删除
语法如下 −
语法
if ((front= = NULL))
printf("Deletion is not possible, Queue is empty");
else{
temp = front;
front = front ->link;
free (temp);
}显示
语法如下 −
语法
while (front! = NULL){
printf("%d", front ->data);
front = front->link;
}程序
以下是使用链表进行队列的 C 程序 −
#include <stdio.h>
#include <stdlib.h>
struct node{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void enq(int data);
void deq();
void display();
void create();
int count = 0;
void main(){
int no, ch, e;
printf("
1 - Enqueue");
printf("
2 - Dequeue");
printf("
3 - Display");
printf("
4 - Exit");
printf("
5-front");
create();
while (1){
printf("
Enter choice : ");
scanf("%d", &ch);
switch (ch){
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
case 5:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("
No front element in Queue");
break;
default:
printf("Wrong choice, Try again ");
break;
}
}
}
void enq(int data){
if (rear == NULL){
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}else{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}
void display(){
front1 = front;
if ((front1 == NULL) && (rear == NULL)){
printf("Queue is empty");
return;
}
while (front1 != rear){
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}
void deq(){
front1 = front;
if (front1 == NULL){
printf("
Error");
return;
}
else
if (front1->ptr != NULL){
front1 = front1->ptr;
printf("
Dequeued value : %d", front->info);
free(front);
front = front1;
}else{
printf("
Dequeued value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
int frontelement(){
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}输出
执行以上程序,将生成以下结果 −
1 - Enque 2 - Deque 3 – Display 4 - Exit 5 - Front element Enter choice: 1 Enter data: 14 Enter choice: 1 Enter data: 85 Enter choice: 1 Enter data: 38 Enter choice: 5 Front element: 14 Enter choice: 3 14 85 38 Enter choice: 2 Dequed value: 14 Enter choice: 3 Enter choice: 4
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP