import java.util.*; public class StackQueueClient { public static void main(String[] args) { // Make a queue with the numbers 1 through 5 // Make an empty stack Queue q = makeQueue(); Stack s = new Stack<>(); System.out.println("initial q = " + q); System.out.println("initial s = " + s); System.out.println(); // Sum up the queue System.out.println("sum of the queue"); System.out.println("before"); System.out.println(" q = " + q); int qSum = sum(q); System.out.println("after"); System.out.println(" q = " + q); System.out.println(" sum = " + qSum); System.out.println(); // Move everything from the queue to the stack System.out.println("queue to stack"); System.out.println("before"); System.out.println(" q = " + q); System.out.println(" s = " + s); queueToStack(q, s); System.out.println("after"); System.out.println(" q = " + q); System.out.println(" s = " + s); System.out.println(); // Sum up the stack System.out.println("sum of the stack"); System.out.println("before"); System.out.println(" s = " + s); int sSum = sum(s); System.out.println("after"); System.out.println(" s = " + s); System.out.println(" sum = " + sSum); } public static Queue makeQueue() { Queue q = new LinkedList<>(); for (int i = 1; i <= 5; i++) { q.add(i); } return q; } public static int sum(Queue q) { int sum = 0; for (int i = 0; i < q.size(); i++) { int n = q.remove(); sum += n; q.add(n); } return sum; } // pollev.com/cse143 public static int sum(Stack s) { int sum = 0; Queue q = new LinkedList<>(); int oldSize = s.size(); // need to save the old size! for (int i = 0; i < oldSize; i++) { // or: while (!s.isEmpty()) { int n = s.pop(); sum += n; q.add(n); } // put everything back in the stack and save order queueToStack(q, s); stackToQueue(s, q); queueToStack(q, s); return sum; } public static void queueToStack(Queue q, Stack s) { while (!q.isEmpty()) { // Two line version // int n = q.remove(); // s.push(n); // One line version s.push(q.remove()); } } public static void stackToQueue(Stack s, Queue q) { while (!s.isEmpty()) { // Two line version // int n = s.pop(); // q.add(n); // One line version q.add(s.pop()); } } }