// Zorah Fung, CSE 143 // Demonstrates basic stack and queue manipulations import java.util.*; public class StackQueueSum { public static void main(String[] args) { Queue q = fillQueue(10); Stack s = fillStack(10); System.out.println("initial queue: " + q); System.out.println("sum = " + queueSum(q)); System.out.println("queue: " + q); System.out.println(); System.out.println("initial stack: " + s); System.out.println("sum = " + stackSum(s)); System.out.println("stack: " + s); } // Creates and returns a queue with the values 1 - n (front to back) // Pre: n >= 1; public static Queue fillQueue(int n) { Queue q = new LinkedList(); for (int i = 1; i <= n; i++) { q.add(i); } return q; } // Creates and returns a stack with the values 1 - n (bottom to top) // Pre: n >= 1; public static Stack fillStack(int n) { Stack s = new Stack(); for (int i = 1; i <= n; i++) { s.push(i); } return s; } // Returns the sum of the values of the given queue public static int queueSum(Queue q) { int sum = 0; for (int i = 0; i < q.size(); i++) { int num = q.remove(); sum += num; q.add(num); } return sum; } // Returns the sum of the values of the given stack public static int stackSum(Stack s) { int sum = 0; Queue q = new LinkedList(); while (!s.isEmpty()) { int num = s.pop(); sum += num; q.add(num); } queueToStack(q, s); stackToQueue(s, q); queueToStack(q, s); return sum; } // Transfers all the values from the given queue to the given stack public static void queueToStack(Queue q, Stack s) { while (!q.isEmpty()) { s.push(q.remove()); } } // Transfers all the values from the given stack to the given queue public static void stackToQueue(Stack s, Queue q) { while (!s.isEmpty()) { q.add(s.pop()); } } }