// Helene Martin, CSE 143 // Basic problems using stack/queue traversals. import java.util.*; public class StacksQueues { public static void main(String[] args) { 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 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); } // Returns the max of values in a stack of integers. // Post: stack is unchanged. // (We thought about saving the values in a temp queue but noticed // that would reverse their order.) public static int max(Stack nums) { int max = 0; Stack temp = new Stack(); while (!nums.isEmpty()) { int value = nums.pop(); temp.push(value); if (value > max) { max = value; } } // restore the original stack while (!temp.isEmpty()) { nums.push(temp.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; int size = q.size(); for (int i = 0; i < size; i++) { int value = q.remove(); sum += value; q.add(value); // save values directly back to the queue } return sum; } // Creates and returns a stack with the specified number of random values // in the range 0-29. 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. 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; } }