// Hunter Schafer, CSE 143 // This class shows an example of how to work with Stacks and Queues import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class StackQueueSum { public static void main(String[] args) { Stack s = fillStack(10); Queue q = fillQueue(10); System.out.println(q); System.out.println(queueSum(q)); System.out.println(q); System.out.println("Initial stack: " + s); System.out.println(stackSum(s)); System.out.println("After stack: " +s); } // Returns the sum of the numbers in 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 numbers in the given stack public static int stackSum(Stack s) { Queue q = new LinkedList(); int sum = 0; int size = s.size(); for (int i = 0; i < size; i++) { int num = s.pop(); sum += num; q.add(num); } while (!q.isEmpty()) { s.push(q.remove()); } while (!s.isEmpty()) { q.add(s.pop()); } while (!q.isEmpty()) { s.push(q.remove()); } return sum; } // Returns a Stack containing the numbers from 1 to max (inclusive) // with 1 at the bottom and max at the top public static Stack fillStack(int max) { Stack s = new Stack(); for (int i = 1; i <= max; i++) { s.push(i); } return s; } // Returns a Queue with the numbers 1 to max (inclusive) // with 1 at the front and max at the back. public static Queue fillQueue(int max) { Queue q = new LinkedList(); for (int i = 1; i <= max; i++) { q.add(i); } return q; } }