-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathqueue_linked_list.c
141 lines (114 loc) · 2.43 KB
/
queue_linked_list.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/* Queue using Linked List - Program to create a queue ADT using linked list.
ADT should support the following operations 1) Createqueue 2) Insert into the
queue 3) Delete from the queue 4) destroyqueue
*/
/* queue q declared globally */
#include <stdio.h>
#include <stdlib.h>
#define NULL 0
struct node
{
int data;
struct node *next;
};
struct queue
{
struct node *front, *rear;
};
struct queue q;
/* This function initializes the queue to empty by making both front and rear as
* NULL */
void createqueue() { q.front = q.rear = NULL; }
int empty()
{
if (q.front == NULL)
return 1;
else
return 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; /* New node is always last node */
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) /* Queue contained only one node */
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;
}