Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method duplicateStack that returns a new stack containing the same eleme

ID: 3938704 • Letter: W

Question

Write 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. JAVA

Explanation / Answer

public static Stack duplicateStack(Stack oldStack){
       ArrayList q = new ArrayList();
       Stack toReturn = new Stack();
       while(!oldStack.empty()){
           int top = (int) oldStack.pop();
           q.add(top);
       }
       while(q.size() > 0){
           oldStack.push(q.get(0));
           q.remove(0);
       }
       while(!oldStack.empty()){
           int top = (int) oldStack.pop();
           q.add(top);
       }
       while(q.size() > 0){
           oldStack.push(q.get(0));
           toReturn.push(q.get(0));
           q.remove(0);
       }
       return toReturn;
   }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote