// Hunter Schafer. CSE 143 // Program that demonstrates stack/queue operations import java.util.*; public class StackQueueExample { public static void main(String[] args) { Queue q = makeQueue(5); Stack s = new Stack(); System.out.println("initial q = " + q); System.out.println("initial s = " + s); System.out.println(); System.out.println("sum of queue = " + sum(q)); System.out.println("q after sum = " + q); System.out.println(); // Hunter: Moved the code to move from queue to stack into a method queueToStack(q, s); System.out.println("after q2s q = " + q); System.out.println("after q2s s = " + s); System.out.println(); System.out.println("sum of stack = " + sum(s)); System.out.println("s after sum= " + s); } // post: returns a Queue containing the numbers 1 to n public static Queue makeQueue(int n) { Queue q = new LinkedList(); for (int i = 1; i <= n; i++) { q.add(i); } return q; } // post: All values from q moved to s (added in queue order). public static void queueToStack(Queue q, Stack s) { // Hunter: Added after lecture while (!q.isEmpty()) { int n = q.remove(); s.push(n); } } // post: All values from s moved to q (added in stack order) public static void stackToQueue(Stack s, Queue q) { // Hunter: Added after lecture while (!s.isEmpty()) { int n = s.pop(); q.add(n); } } // post: returns the sum of the values in 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; } // pre : s is not null // post: returns the sum of the values in s public static int sum(Stack s) { Queue q = new LinkedList(); int sum = 0; // Hunter: Without size variable, for loops exits early int size = s.size(); for (int i = 0; i < size; i++) { int n = s.pop(); sum += n; q.add(n); } queueToStack(q, s); // Must go back and forth in the queue again to get the proper order stackToQueue(s, q); queueToStack(q, s); return sum; } }