Write a java program with a method duplicateStack that returns a new stack conta
ID: 3774299 • Letter: W
Question
Write a java program with a method duplicateStack that returns a new stack containing the same elements and in the same order as the stack specified in the parameter. The method should create a new stack and fill it with the same data elements as the given stack. (You do not need to duplicate the contents of the elements.) Before the method finishes, it must restore the contents of the original stack to its original state (same contents in the same order). Besides the new stack that the method returns, the only additional data structure that it can use is a single queue. The method may also use O(1) additional space.
Explanation / Answer
import java.util.Queue;
import java.util.Stack;
import java.util.LinkedList;
/**
*
*/
/**
* @author JKishore
*
*/
public class Tester {
/**
* @param args
*/
public static void main(String[] args) {
Stack<String>stack=new Stack<>();
stack.push("a");
stack.push("c");
stack.push("b");
System.out.println("Original stack : "+stack);
System.out.println("Duplicate stack : "+duplicateStack(stack));
System.out.println("Original stack after duplicate method : "+stack);
}
//method to create duplicate stack
public static Stack<String> duplicateStack(Stack<String>stack){
Stack<String>duplicateStack=new Stack<>(); // initialize duplicate stack
Queue<String> queue = new LinkedList<>();
if(stack==null || stack.size()==0){ // throws exception when the stack is not valid
throw new IllegalArgumentException();
}
int size=stack.size(); // getting the size of the stack
while(size>0){ // loop to iterate over stack
queue.add(stack.pop());//adding in queue and popping the stack
duplicateStack.add(0,queue.peek()); // adding at first position and taking the value from the queue
stack.add(0, queue.remove()); // adding at first position of original stack to retain the old values
size--;
}
return duplicateStack; // returning the duplicate stack
}
}
------------------------------------------------------------output------------------------------------------------------------------
Original stack : [a, c, b]
Duplicate stack : [a, c, b]
Original stack after duplicate method : [a, c, b]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.