Learn-dsa..in 30 days!



























CC-5 : Implement Stack using Queue.

Description:

Create and test a Stack using Queue.

Test cases and expected outputs:

Input Parameters Expected outputs
StackQueue stack=new StackQueue();
stack.add(9);
stack.add(14);
stack.add(17);
stack.add(34);
stack.add(21);
stack.add(28);
Stack nodes: (top of stack)28 <- 21 <- 34 <- 17 <- 14 <- 9 <-
stack.remove();
stack.remove();
stack.remove();
Stack nodes: 17 <- 14 <- 9

Pseudocode:

The Stack will use a Queue for storing data elements.
The add() method: By default the Queue.add(), adds new nodes to end of the Queue. But we want the Queue to act as a Stack, so we need to do following steps: add the new node using the Queue.add(). Now new node is the last node of the Queue. So, remove all other nodes using Queue.remove() and add them again back using Queue.add(). Now the new node will be the first node and all other nodes will be after it. Thus our implementation of add() method is showing same functionality as stack.add() method.
The remove() method: call Queue.remove() method, this will return first element, which is same as required stack behaviour.

Code:

public class StackQueue {	
	
private Queue<Integer> queue=new LinkedList();
	
public int get() {
	if (queue.size() !=0) {
		return queue.peek();
	}
	return Integer.MIN_VALUE;
}

public boolean add(int data){
	queue.add(data);
	for (int idx=0; idx< queue.size()-1; idx++) {
		queue.add(queue.peek());
		queue.remove();
	}
	return true;
}

public int remove() {
	return queue.remove();
}
}

Click here to download and run code and test cases !