-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18_priority_queue.c
More file actions
125 lines (116 loc) · 2.71 KB
/
18_priority_queue.c
File metadata and controls
125 lines (116 loc) · 2.71 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
#include<stdio.h>
// Item Definition
struct Item
{
int data;
int priority;
struct Item *addr_next;
}*left, *right;
// Function to Enqueue Item into the Queue
void enqueue()
{
struct Item *ptr;
ptr = (struct Item *)malloc(sizeof(struct Item));
printf("\nEnter Item : ");
scanf("%d", &ptr->data);
printf("Enter Priority : ");
scanf("%d", &ptr->priority);
if(left == NULL)
{
ptr->addr_next = NULL;
left = right = ptr;
}
else if(ptr->priority > right->priority)
{
right->addr_next = ptr;
ptr->addr_next = NULL;
right = ptr;
}
else if(ptr->priority < left->priority)
{
ptr->addr_next = left;
left = ptr;
}
else
{
struct Item *pri_ptr, *sec_ptr;
sec_ptr = left;
pri_ptr = sec_ptr->addr_next;
while(pri_ptr != right->addr_next)
{
if((ptr->priority > sec_ptr->priority) && (ptr->priority <= pri_ptr->priority))
{
sec_ptr->addr_next = ptr;
ptr->addr_next = pri_ptr;
return;
}
else
{
sec_ptr = pri_ptr;
pri_ptr = pri_ptr->addr_next;
}
}
}
printf("Item Enqueued Successfully\n\n");
}
// Function to Dequeue Item from Queue
void dequeue()
{
if(left == NULL)
{
printf("\nQueue Underflow\n\n");
return;
}
else if(left == right)
{
free(left);
left = right = NULL;
}
else
{
struct Item *pri_ptr, *sec_ptr;
sec_ptr = left;
pri_ptr = sec_ptr->addr_next;
while(pri_ptr != right)
{
sec_ptr = pri_ptr;
pri_ptr = pri_ptr->addr_next;
}
sec_ptr->addr_next = NULL;
free(pri_ptr);
right = sec_ptr;
}
printf("\nItem Dequeued Successfully\n\n");
}
// Function to peek into the Stack
void peek()
{
if (left == NULL)
printf("\nQueue Underflow\n\n");
else
printf("\nElement with Highest Priority\nValue : %d\nPriority : %d\n\n", right->data, right->priority);
}
int main()
{
int choice;
left = NULL;
right = NULL;
while(1)
{
printf("Enter\n");
printf("1. To Enqueue Item\n");
printf("2. To Dequeue Item\n");
printf("3. To Peek into Queue\n");
printf("0. To Exit\n");
printf("Enter Your Choice : ");
scanf("%d", &choice);
switch(choice)
{
case 0 : return 0;
case 1 : enqueue(); break;
case 2 : dequeue(); break;
case 3 : peek(); break;
default : printf("\nInvalid Choice, Try Again\n\n");
}
}
}