- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathStack_using_priorityqueue.java
More file actions
Latest commit
89 lines (79 loc) · 2.63 KB
/
Copy pathStack_using_priorityqueue.java
File metadata and controls
89 lines (79 loc) · 2.63 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
// ====================== Problem Statement ==========================
/*
Here we will take the numbers input from user and with the help of priority queue we need to implement stack.
Priority queue is a special type of queue in which the numbers are dequeue based on their priority. Every no has some priority along with its data.
The data having the highest priority is popped first.
In priority queue, we assign priority to the elements that are being pushed. A stack requires elements to be processed in Last in First Out manner.
The idea is to associate a count that determines when it was pushed. This count works as a key for the priority queue. So the implementation of
stack uses a priority queue of pairs, with the first element serving as the key.
For ex:
User enters input : 4 1 2
so in queue -> [(2,3) (1,2) (4,1)]
*/
// // ====================== Code with Java ==========================
importjava.util.PriorityQueue;
importjava.util.Scanner;
classMain
{
// count is used as key for the priority queue.
intcount;
PriorityQueue<int[]> pq = newPriorityQueue<>((a, b) -> b[0]-a[0]);
publicMain() {
count = 1;
}
publicbooleanisEmpty() {
returnpq.isEmpty();
}
//function to insert element in queue
publicvoidpush(intn) {
int[] arr = newint[]{ count++,n };
pq.add(arr);
}
//function to delete element from queue
publicvoidpop() {
if (pq.isEmpty()) {
System.out.println("Empty Stack");
return;
}
count--;
pq.poll();
}
//function to find top element
publicinttop(){
if (pq.isEmpty()) {
System.out.println("Empty Stack");
return -1;
}
int[] temp = pq.peek();
returntemp[1];
}
publicstaticvoidmain(String[] args) {
Mains = newMain();
intchoice;
Scannersc = newScanner(System.in);
System.out.println("Enter your choice : ");
System.out.println("1-push 2-pop 3-peek");
choice = sc.nextInt();//choice is used to store the value of next function to pe performed
intelement;
while(choice!=0){
if(choice==1){//insert element
System.out.println("Enter element : ");
element=sc.nextInt();
s.push(element);
}
elseif(choice==2){//delete element
s.pop();
}
elseif(choice==3){//find topmost element
if(s.top()!=-1)
System.out.println(s.top());
}
else{//terminate the loop
System.out.println("Invalid choice!");
}
System.out.println("Enter your choice : ");
System.out.println("0-Exit 1-push 2-pop 3-peek");
choice = sc.nextInt();
}
}
}