import java.util.Queue; import java.util.ArrayDeque; // Stack: push/pop/peek/isEmpty/EmptyStackException // Queue: add/remove/element/isEmpty/NoSuchElementException public class Worksheet02 { public static void printStack(Stack stack) { System.out.println("Stack:"); Stack stackBuffer = new CarlStack(); Queue queueBuffer = new ArrayDeque(); if (stack.isEmpty()) { System.out.println("[empty]"); return; } // stack: top, middle, bottom // go through the stack and figure out max length int maxLength = 0; while (!stack.isEmpty()) { String item = stack.pop(); if (item.length() > maxLength) maxLength = item.length(); queueBuffer.add(item); } // stack: [] // queueBuffer: top, middle, bottom String fmt = "| %" + maxLength + "s |\n"; while (!queueBuffer.isEmpty()) { String item = queueBuffer.remove(); System.out.format(fmt, item); stackBuffer.push(item); } // queueBuffer: [] // stackBuffer: bottom, middle, top for (int i = 0; i < maxLength + 4; i++) System.out.print("-"); System.out.println(); while (!stackBuffer.isEmpty()) { stack.push(stackBuffer.pop()); } // stackBuffer: [] // stack: top, middle, bottom } public static void printQueue(Queue queue) { System.out.println("Queue:"); Queue queueBuffer = new ArrayDeque(); if (queue.isEmpty()) { System.out.println("[empty]"); return; } // queue: a, b, c // go through the queue and figure out totalLength; int totalLength = 0; while (!queue.isEmpty()) { String item = queue.remove(); totalLength += item.length() + 1; queueBuffer.add(item); } // queueBuffer: a, b, c for (int i = 0; i < totalLength + 1; i++) System.out.print("-"); System.out.println(); while (!queueBuffer.isEmpty()) { String item = queueBuffer.remove(); System.out.print(" "); System.out.print(item); queue.add(item); } // queueBuffer: [] // queue: a, b, c System.out.println(); for (int i = 0; i < totalLength + 1; i++) System.out.print("-"); System.out.println(); } public static void printStates(Stack stack, Queue queue) { printStack(stack); printQueue(queue); System.out.println(); } public static void main(String[] args) { Stack stack = new CarlStack(); Queue queue = new ArrayDeque(); queue.add("tofu"); queue.add("broccoli"); queue.add("rice"); // (a) Draw the states of stack and queue printStates(stack, queue); System.out.println(queue.element()); while (!queue.isEmpty()) { stack.push(queue.remove()); } // (b) Draw the states of stack and queue printStates(stack, queue); for (int i = 0; i < 2; i++) { queue.add(stack.peek()); } // (c) Draw the states of stack and queue printStates(stack, queue); } }