// Helene Martin, CSE 143 // Demonstrates basic usage of stacks and queues import java.util.*; public class StacksQueues { public static void main(String[] args) { Stack tas = new Stack(); tas.push("Molly"); // bottom of stack tas.push("Zack"); tas.push("Andrew"); // top of stack System.out.println(tas); System.out.println(tas.pop()); // Andrew (top) System.out.println(tas); Stack nums = createRandomStack(12); System.out.println("Random stack: " + nums); int max = max(nums); System.out.println("Max: " + max); System.out.println("Stack after max: " + nums); System.out.println(); Queue taQueue = new LinkedList(); taQueue.add("Molly"); // front of queue taQueue.add("Zack"); taQueue.add("Andrew"); // back of queue System.out.println(taQueue); System.out.println(taQueue.remove()); // Molly (front) System.out.println(taQueue); Queue q = createRandomQueue(12); System.out.println("Random queue: " + q); int sum = sum(q); System.out.println("Sum " + sum); System.out.println("Queue after sum: " + q); } // Creates and returns a stack with the specified number of random values // in the range 0-29. // pre: size >= 0 public static Stack createRandomStack(int size) { Stack nums = new Stack(); Random r = new Random(); for (int i = 0; i < size; i++) { nums.push(r.nextInt(30)); } return nums; } // Creates and returns a queue with the specified number of random values // in the range 0-29. // pre: size >= 0 public static Queue createRandomQueue(int size) { Queue q = new LinkedList(); Random r = new Random(); for (int i = 0; i < size; i++) { q.add(r.nextInt(30)); } return q; } // Returns the max of values in a stack of integers. // post: stack is unchanged. public static int max(Stack nums) { int max = nums.peek(); Stack backup = new Stack(); while (!nums.isEmpty()) { int value = nums.pop(); backup.push(value); // save if (value > max) { max = value; } } // restore the stack while (!backup.isEmpty()) { nums.push(backup.pop()); } return max; } // Returns the sum of all values in a queue of integers. // post: queue is unchanged public static int sum(Queue q) { int sum = 0; for (int i = 0; i < q.size(); i++) { int value = q.remove(); sum += value; q.add(value); // can use the queue itself for storage } // while (!q.isEmpty()) { // sum += q.remove(); // } return sum; } }