Learn-dsa..in 30 days!



























CC-7 : Implement Stacks using PriorityQueue.

Description:

Given Stack elements that each have a node integer data and integer priority. The node’s priority value will be used to order the stack node in the Stack. Create and test a priority ordered Stack using a PriorityQueue.

Test cases and expected outputs:

Input Parameters Expected outputs
StackUsingPriorityQueue stack=
new StackUsingPriorityQueue();
stack.addByPriority(99,33);
stack.addByPriority(14, 10);
stack.addByPriority(77, 44);
stack.addByPriority(34, 55);
stack.addByPriority(21, 66);
stack.addByPriority(82, 33);
stack.printStack();
Stack nodes: 21 Priority: 66
34 Priority: 55
77 Priority: 44
82 Priority: 33
99 Priority: 33
14 Priority: 10

Pseudocode:

The Stack will use a PriorityQueue for storing data elements in a priority sorted manner. PriorityQue accepts a comparator called StackPrioComparator to sort input elements by priority.
addByPriority() method:
Create a StackPriorityNode instance, and set the nodes data and priority to it.
Call PriorityQueue .add() with StackPriorityNode instance, this will ad nodeinpropersorted priority manner into PriorityQueue, using the StackPrioComparator.
remove() method: Return value returned by PriorityQueue.remove().

Code:

public class StackUsingPriorityQueue {	
	
private PriorityQueue<StackPriorityNode> pq=
new PriorityQueue< StackPriorityNode >(new StackPrioComparator());	

public StackPriorityNode get() {
	return pq.peek();
}

public boolean addByPriority(int data, int priority){
	StackPriorityNode node=new StackPriorityNode();
	node.setNodeData(data);
	node.setPriority(priority);
	pq.add(node);
	return true;
}

public StackPriorityNode remove() {
	return pq.poll();
}

public int getSize() {
	return pq.size();
}

public void traverse() {
	Iterator<StackPriorityNode> itr=pq.iterator();
	while (itr.hasNext()) {
  		System.out.println(((StackPriorityNode)itr.next()).getNodeData());
  		
  	}
}			

private class StackPrioComparator implements Comparator {	
	public int compare(Object stackNode1, Object stackNode2) {
		int frstNm= ((StackPriorityNode)stackNode1).getPriority();
		int scndNm= ((StackPriorityNode)stackNode2).getPriority();
		int retVal=0;
		if (frstNm < scndNm) {retVal =1;} else {
			if (frstNm == scndNm) {retVal = 0;} else {
				if (frstNm > scndNm) {retVal = -1;}
			}
		}		
	return retVal;
	}	
}  
}

Click here to download and run code and test cases !