/* * Kyle Pierce * CSE 143 * * Client program which looks at some more complicated * operations with stacks and queues */ import java.util.*; public class StackQueue { public static void main(String[] args) { Queue q = makeQueue(10); System.out.println("initial queue = " + q); System.out.println("sum = " + sum(q)); System.out.println("after sum queue = " + q); System.out.println(); Stack s = new Stack(); queueToStack(q, s); System.out.println("after queueToStack:"); System.out.println(" queue = " + q); System.out.println(" stack = " + s); System.out.println(); s = makeStack(10); System.out.println("initial stack = " + s); System.out.println("sum = " + sum(s)); System.out.println("after sum stack = " + s); System.out.println(); stackToQueue(s, q); System.out.println("after stackToQueue:"); System.out.println(" stack = " + s); System.out.println(" queue = " + q); } // pre : max >= 1 // post: returns a queue of the numbers 1 to max inclusive // where 1 is at the front and max is at the back public static Queue makeQueue(int max) { Queue q = new LinkedList(); for (int i = 1; i <= max; i++) { q.add(i); } return q; } // pre : max >= 1 // post: returns a stack of the numbers 1 to max inclusive // where 1 is at the bottom and max is at the top public static Stack makeStack(int max) { Stack s = new Stack(); for (int i = 1; i <= max; i++) { s.push(i); } return s; } // post: moves all values from q to s from front to back // emptying q in the process public static void queueToStack(Queue q, Stack s) { while (!q.isEmpty()) { int n = q.remove(); s.push(n); } } // post: moves all values from s to q from top to bottom // emptying s in the process public static void stackToQueue(Stack s, Queue q) { 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 = sum + n; q.add(n); } return sum; } // post: returns the sum of the values in s public static int sum(Stack s) { int sum = 0; Queue q = new LinkedList(); while (!s.isEmpty()) { int n = s.pop(); sum = sum + n; q.add(n); } queueToStack(q, s); stackToQueue(s, q); queueToStack(q, s); return sum; } }