Priority Queue using DLL
Priority Queue using DLL
• Priority queue is abstract data type which behave similar to the linear queue except
that each element has priority.
Example:
Hospital Emergency Queue
The patients will be treated according to their medical condition. (i.e: Person in pain
– High priority).
Priority Queue using DLL
Example:
Priority 1 2 3 4 5
Front Rear
Deletion Insertion
The priority of the elements in the priority queue will determine the
order of removal of the data elements.
1 import [Link].*;
2 class Main {
3
4 static class Node {
5 int data;
6
7 int priority;
8 Node next, prev;
9 public Node(int data, int priority) {
10
11 [Link] = data;
12 [Link] = priority;
13
14 }
15 }
16
private static Node head = null;
17
18
19
20
21
22
1 private static void push(int data, int priority) {
2 if (head == null) {
3
4 Node newNode = new Node(data, priority);
5 head = newNode;
6
7 return;
8 }
9 Node node = new Node(data, priority);
10
11 Node temp = head, parent = null;
12 while (temp != null && [Link] >= priority) {
13
14 parent = temp;
15 temp = [Link];
16
}
17
18 if (parent == null) {
19 [Link] = head;
20
21 [Link] = node;
22 head = node; }
1 else if (temp == null) {
2 [Link] = node;
3
4 [Link] = parent;
5 }
6
7 else {
8 [Link] = node;
9 [Link] = parent;
10
11 [Link] = temp;
12 [Link] = node;
13
14 }
15 }
16
private static int peek() {
17
18 if (head != null) {
19 return [Link];
20
21 }
22 return -1; }
1 private static int pop() {
2 if (head != null) {
3
4 int curr = [Link];
5 head = [Link];
6
7 if (head != null)
8 [Link] = null;
9 return curr;
10
11 }
12 return -1;
13
14 }
15 public static void main(String[] args) {
16
Scanner sc=new Scanner([Link]);
17
18 int n=[Link]();
19 for(int i=0;i<n;i++)
20
21 {
22 int data=[Link]();
1 int pri=[Link]();
2 push(data, pri);
3
4 }
5 [Link](peek());
6
7 [Link](pop());
8 [Link](pop());
9 [Link](peek());
10
11 }
12 }
13
14
15
16
17
18
19
20
21
22
THANK YOU