-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_list.c
More file actions
142 lines (126 loc) · 2.73 KB
/
queue_list.c
File metadata and controls
142 lines (126 loc) · 2.73 KB
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
#include <stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
};
struct queue {
struct node *front, *rear;
};
struct queue *initialise(){
struct queue *q=(struct queue*)malloc(sizeof(struct queue));
q->front=NULL;
q->rear=NULL;
return q;
}
int isEmpty(struct queue* q)
{
if (q->front == NULL) {
return 1;
}
return 0;
}
struct node *createNode(int data)
{
struct node *newNode=(struct node*)malloc(sizeof(struct node));
if(newNode==NULL)
{
printf("Memory not allocated. \n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void enqueue(struct queue* q, int new_data)
{
struct node *new_node = createNode(new_data);
if (q->rear == NULL) {
q->front = q->rear = new_node;
return;
}
q->rear->next = new_node;
q->rear = new_node;
}
void dequeue(struct queue* q)
{
if (isEmpty(q)) {
printf("Queue Underflow\n");
return;
}
struct node *temp = q->front;
q->front = q->front->next;
if (q->front == NULL)
q->rear = NULL;
free(temp);
}
void getFront(struct queue* q)
{
if (isEmpty(q)) {
printf("Queue is empty\n");
return;
}
printf("%d is the front element of the queue. \n",q->front->data);
}
void getRear(struct queue* q)
{
if (isEmpty(q)) {
printf("Queue is empty\n");
return;
}
printf("%d is the last element of the queue. \n",q->rear->data);
}
void display(struct queue *q) {
if (isEmpty(q)) {
printf("Queue is empty! \n");
return;
}
printf("Queue: ");
struct node *temp=(q->front);
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
}
void freeQueue(struct queue *q) {
while (!isEmpty(q)) {
dequeue(q);
}
free(q);
}
int main()
{
struct queue *q = initialise();
int choice, data;
do {
printf("\n1. Enqueue\n2. Dequeue\n3. Display\n4. Get front element \n5. Get rear element \n6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to enqueue: ");
scanf("%d", &data);
enqueue(q, data);
break;
case 2:
dequeue(q);
break;
case 3:
display(q);
break;
case 4:
getFront(q);
break;
case 5:
getRear(q);
break;
case 6:
freeQueue(q);
exit(0);
default:
printf("Enter a valid choice!\n");
}
} while (choice != 6);
return 0;
}