-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueWithLinkedList.c
166 lines (148 loc) · 2.86 KB
/
QueueWithLinkedList.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *link;
};
struct Node *front = NULL;
struct Node *rear = NULL;
struct Node *CreateNode()
{
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Allocation Failed\n");
}
else
{
printf("Node Created\n");
return newNode;
}
}
void push(int key)
{
struct Node *newNode = CreateNode();
newNode->data = key;
newNode->link = NULL;
if (rear == NULL)
{
rear = newNode;
front = rear;
}
else
{
newNode->link = front;
rear->link = newNode;
rear = newNode;
}
}
int pop()
{
if (front == NULL)
{
return -1;
}
else
{
int key;
struct Node *temp;
temp = front;
front = temp->link;
key = temp->data;
free(temp);
return key;
}
}
int peek()
{
if (front == NULL)
{
return -1;
}
else
{
int key;
key = front->data;
return key;
}
}
void display()
{
if (front == NULL)
{
printf("Empty");
}
else
{
struct Node *temp;
temp = front;
do
{
printf("%d->", temp->data);
temp = temp->link;
} while (temp != front);
}
}
int main()
{
while (1)
{
printf("\n");
printf("Enter 1 to push in queue\n");
printf("Enter 2 to pop in queue\n");
printf("Enter 3 to peek in queue\n");
printf("Enter 4 to display whole queue\n");
printf("Enter 5 to Exit\n");
int ch;
scanf("%d", &ch);
printf("\n");
switch (ch)
{
case 1:
{
int element;
printf("\nEnter the Element to Push : ");
scanf("%d", &element);
push(element);
break;
}
case 2:
{
int key = pop();
if (key == -1)
{
printf("\nQueue is Empty\n");
}
else
printf("\n%d is pop from the queue.\n", key);
break;
}
case 3:
{
int key = peek();
if (key == -1)
{
printf("\n Queue is Empty\n");
}
else
printf("\nFornt of queue is : %d\n", key);
break;
}
case 4:
{
printf("\nQueue is : ");
display();
}
case 5:
{
exit(1);
break;
}
default:
break;
}
}
return 0;
}