// cse 142: control abstraction // cse 143: data abstraction // ADTs (abstract data types): list, stacks, queues // FIFO: first in, first out -> queues, lines // LIFO: last in, first out -> stacks, cafeteria trays // Jeremy Lipschutz // This program gives us practice // with the operations via small methods // that work with Stacks and Queues import java.util.*; public class StackQueue { public static void main(String[] args) { Queue q = makeQueue(6); System.out.println("before sum = " + q); System.out.println(sum(q)); System.out.println("after sum = " + q); Stack s = new Stack(); System.out.println(); System.out.println("before queueToStack"); System.out.println("queue = " + q); System.out.println("stack = " + s); queueToStack(q, s); System.out.println("after queueToStack"); System.out.println("queue = " + q); System.out.println("stack = " + s); System.out.println(); System.out.println(); Stack s2 = makeStack(6); Queue q2 = new LinkedList(); System.out.println("before sum = " + s2); System.out.println(sum(s2)); System.out.println("after sum = " + s2); System.out.println("before stackToQueue"); System.out.println("stack = " + s2); System.out.println("queue = " + q2); stackToQueue(s2, q2); System.out.println("after stackToQueue"); System.out.println("stack = " + s2); System.out.println("queue = " + q2); } // Returns a new Queue containing // integers from 1 inclusive to n inclusive, with // 1 at the front and n at the back. public static Queue makeQueue(int n) { Queue q = new LinkedList(); for(int i = 1; i <= n; i++) { q.add(i); } return q; } // Returns a new Stack containing // integers from 1 inclusive to n inclusive, with // 1 at the bottom and n on the top. public static Stack makeStack(int n) { Stack s = new Stack(); for(int i = 1; i <= n; i++) { s.push(i); } return s; } // Returns the sum of all 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; } // Returns the sum of all the values in the given queue public static int sum(Stack s) { int sum = 0; Queue q = new LinkedList(); // This is another way of looping where we remember the oldSize //int oldSize = s.size(); //for(int i = 0; i < oldSize; i++) { while(!s.isEmpty()) { int n = s.pop(); sum += n; q.add(n); } queueToStack(q, s); stackToQueue(s, q); queueToStack(q, s); return sum; } // Removes all the values from the given queue and adds them to the top // of the given stack public static void queueToStack(Queue q, Stack s) { while(!q.isEmpty()) { int n = q.remove(); s.push(n); // s.push(q.remove()); } } // Removes all the values from the given stack and adds them to the back // of the given queue public static void stackToQueue(Stack s, Queue q) { while(!s.isEmpty()) { int n = s.pop(); q.add(n); // q.add(s.pop()); } } }