-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue_linked.c
111 lines (96 loc) · 1.98 KB
/
queue_linked.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
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Queue
{
struct Node *front, *rear;
};
// Initialize a new queue
struct Queue *createQueue()
{
struct Queue *q = (struct Queue *)malloc(sizeof(struct Queue));
q->front = q->rear = NULL;
return q;
}
void enqueue(struct Queue *q, int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (q->rear == NULL)
{
q->front = q->rear = newNode;
return;
}
q->rear->next = newNode;
q->rear = newNode;
}
int dequeue(struct Queue *q)
{
if (q->front == NULL)
{
printf("Queue Underflow\n");
return -1;
}
struct Node *temp = q->front;
int data = temp->data;
q->front = q->front->next;
if (q->front == NULL)
{
q->rear = NULL;
}
free(temp);
return data;
}
void displayQueue(struct Queue *q)
{
if (q->front == NULL)
{
printf("Queue is empty.\n");
return;
}
struct Node *temp = q->front;
printf("Queue elements: ");
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main()
{
struct Queue *queue = createQueue();
int choice, value;
while (1)
{
printf("\n1. Enqueue\n2. Dequeue\n3. Display Queue\n4. Exit\nEnter choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(queue, value);
break;
case 2:
value = dequeue(queue);
if (value != -1)
{
printf("Dequeued: %d\n", value);
}
break;
case 3:
displayQueue(queue);
break;
case 4:
exit(0);
default:
printf("Invalid choice\n");
}
}
}