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

Q: Transfer All the elements from Stack1 to Stack2 and elements of Stack2 should

ID: 3653333 • Letter: Q

Question

Q: Transfer All the elements from Stack1 to Stack2 and elements of Stack2 should have the same order as it was in Stack1 Guys, I'm pretty close to this, My code only works for a specific size of stack not all sizes. This code is for a stack with 3 elements //save the top top = stack1.pop(); stack2.push(stack1.pop()); stack2.push(stack1.pop()); //push it back stack1.push(top); stack1.push(stack2.pop()); stack1.push(stack2.pop()); //save the top top = stack1.pop(); stack2.push(stack1.pop()); // The bottom is left in Stack1 stack2.push(top); stack1.push(stack2.pop()); stack1.push(stack2.pop());

Explanation / Answer

import java.util.NoSuchElementException; public class QueueWithTwoStacks { private Stack stack1; // back of queue private Stack stack2; // front of queue // create an empty queue public QueueWithTwoStacks() { stack1 = new Stack(); stack2 = new Stack(); } // move all items from stack1 to stack2 private void moveStack1ToStack2() { while (!stack1.isEmpty()) stack2.push(stack1.pop()); } // is the queue empty? public boolean isEmpty() { return stack1.isEmpty() && stack2.isEmpty(); } // return the number of items in the queue. public int size() { return stack1.size() + stack2.size(); } // return the item least recently added to the queue. public Item peek() { if (isEmpty()) throw new NoSuchElementException("Queue underflow"); if (stack2.isEmpty()) moveStack1ToStack2(); return stack2.peek(); } // add the item to the queue public void enqueue(Item item) { stack1.push(item); } // remove and return the item on the queue least recently added public Item dequeue() { if (isEmpty()) throw new NoSuchElementException("Queue underflow"); if (stack2.isEmpty()) moveStack1ToStack2(); return stack2.pop(); } // a test client public static void main(String[] args) { QueueWithTwoStacks q = new QueueWithTwoStacks(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) q.enqueue(item); else if (!q.isEmpty()) StdOut.print(q.dequeue() + " "); } StdOut.println("(" + q.size() + " left on queue)"); } }