// Demonstrates basic usage of stacks and queues import java.util.*; public class StacksQueues { public static void main(String[] args) { // Queue operations. Queue q = createRandomQueue(10); System.out.println("q = " + q); int sum = sum(q); System.out.println("sum = " + sum); System.out.println("q = " + q); Stack s = new Stack(); queueToStack(q, s); System.out.println(" after q->s: q = " + q); System.out.println(" after q->s: s = " + s); // Same with the stack Stack s2 = createRandomStack(10); System.out.println("s = " + s2); int sum2 = sum(s2); System.out.println("sum = " + sum2); System.out.println("s = " + s2); Queue q2 = new LinkedList(); stackToQueue(q2, s2); System.out.println(" after q->s: s = " + s2); System.out.println(" after q->s: q = " + q2); } // pre: size >= 0 // Creates and returns a queue with the specified number of random values // in the range 0-29. public static Queue createRandomQueue(int size) { Queue q = new LinkedList(); Random rand = new Random(); for (int i = 0; i < size; i++) { q.add(rand.nextInt(30)); } return q; } // post: Values from q moved to s (added in queue order, front to back) public static void queueToStack(Queue q, Stack s) { while (!q.isEmpty()) { int n = q.remove(); s.push(n); } } // post: returns the sum of the values in the given queue 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: size >= 0 // Creates and returns a stack with the specified number of random values // in the range 0-29. public static Stack createRandomStack(int size) { Stack s = new Stack(); Random rand = new Random(); for (int i = 0; i < size; i++) { s.push(rand.nextInt(30)); } return s; } // post: Values from s moved to q (added in stack order, top to bottom); public static void stackToQueue(Queue q, Stack s) { while (!s.isEmpty()) { int n = s.pop(); q.add(n); } } // post: returns the sum of the values in the given stack public static int sum(Stack s) { int sum = 0; Queue q = new LinkedList(); int size = s.size(); for (int i = 0; i < size; i++) { int n = s.pop(); sum += n; q.add(n); } queueToStack(q, s); stackToQueue(q, s); queueToStack(q, s); return sum; } }