Learn-dsa..in 30 days!



























CC-16 : Reverse order of elements of stack.

Description:

Given a stack with integer elements, reverse the order of elements of the stack and return the same.

Test cases and expected outputs:

Input Parameters Expected outputs
Stack nodes:
9 <- 14 <- 17 <- 34 <- 21 <- 28 <-
Reversed:
28 <- 21 <- 34 <- 17 <- 14 <- 9 <-
Stack nodes:
9 <- 14 <- 17 <- 34 <- 21 <- 28 <- 35 <-
Reversed:
35 <- 28 <- 21 <- 34 <- 17 <- 14 <- 9 <-

Pseudocode:

Initialize a Queue for processing purposes.
While input stack size is not zero:
Remove the top element of stack and add it to the Queue.
While Queue size is not zero:
Remove the first element of Queue and add it to the stack.
Return the updated stack.


Code:

public Deque<Integer> reverse(Deque<Integer> stack) throws Exception{
	Queue<Integer> tempQ=new LinkedList<Integer>();
		
	while (stack.size() !=0) {
		tempQ.offer(stack.poll());		
	}
	while (tempQ.size() !=0) {
		stack.offerFirst((int) tempQ.poll());
	}
	return stack;
}

Click here to download and run code and test cases !