Last active
November 24, 2017 17:36
-
-
Save anil477/fb0ee38c58d0b44afded6293e2e921c4 to your computer and use it in GitHub Desktop.
implement stack using priority queue or heap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.duanqu.tech/questions/244804/how-to-implement-stack-using-priority-queue | |
import java.util.Comparator; | |
import java.util.PriorityQueue; | |
import java.util.Queue; | |
class StackPriorityQueue { | |
PriorityQueue<StackElement> queue = new PriorityQueue<StackElement>(10, new Com()); | |
int order = 1; | |
public void push(int val){ | |
StackElement element = new StackElement(order++,val); | |
queue.add(element); | |
} | |
public Integer pop(){ | |
if(queue.isEmpty()){ | |
System.out.println("Stack Underflow"); | |
return null; | |
} | |
return queue.poll().value; | |
} | |
public static void main(String args[]){ | |
StackPriorityQueue q = new StackPriorityQueue(); | |
q.push(5); | |
q.push(10); | |
q.push(1); | |
q.push(3); | |
q.push(50); | |
q.push(500); | |
q.push(60); | |
q.push(30); | |
q.push(40); | |
q.push(23); | |
q.push(34); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
System.out.println(q.pop()); | |
} | |
} | |
class StackElement{ | |
int key; | |
int value; | |
public StackElement(int key, int value) { | |
this.key = key; | |
this.value = value; | |
} | |
} | |
class Com implements Comparator<StackElement> | |
{ | |
@Override | |
public int compare(StackElement o1, StackElement o2) | |
{ | |
return o2.key - o1.key; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment