Bag Sample
Compute the average and simple standard deviation of the double values on standard input
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Stats { public static void main (String[] args) { Bag<Double> numbers = new Bag<Double>(); while(!StdIn.isEmpty) numbers.add(StdIn.readDouble()); int N = numbers.size(); double sum = 0.0; for (double x : numbers) sum += x; double mean = sum/N; sum = 0.0; for (double x : numbers) sum += (x-mean)*(x-mean); double std = Math.sqrt(sum/(N-1)); StdOut.printf("Mean: %.2f ", mean); StdOut.printf("Std dev: %.2f ", std); } }
FIFO Queues
Sample queue client
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static int[] readInts (String name) { In in = new In(name); Queue<Integer> q = new Queue<Integer>(); while(!in.isEmpty()) q.enqueue(in.readInt()); int N = q.size(); int[] a = new int[N]; for(int i = 0; i < N; i++) a[i] = q.dequeue(); return a; }
LIFO Stacks
Sample stack client
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Reverse { public static void main (String[] args) { Stack<Integer> stack = new Stack<Integer>(); while(!StdIn.isEmpty()) stack.push(StdIn.readIn()); for(int i : stack) StdOut.println(i); } }
Dijkstra's Two-Stack Algorithm for Expression Evaluation
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class evaluate { public static void main(String[] args) { Stack<String> ops = new Stack<String>(); Stack<Double> vals = new Stack<Double>(); while (!StdIn.isEmpty){ String s = StdIn.readString(); if (s.equals("(")); else if (s.equals("+")) ops.push(s); else if (s.equals("-")) ops.push(s); else if (s.equals("*")) ops.push(s); else if (s.equals("/")) ops.push(s); else if (s.equals(")")) ops.push(s); else if (s.equals("sqrt")) ops.push(s); else if (s.equals(")")) { String op = ops.pop(); Double v = vals.pop(); if (op.equals("+")) v = vals.pop() + v; else if (op.equals("-")) v = vals.pop() - v; else if (op.equals("*")) v = vals.pop() * v; else if (op.equals("/")) v = vals.pop() / v; else if (op.equals("sqrt")) v = Math.sqrt(v); vals.push(v); } else vals.push(Double.parseDouble(s)); } StdOut.println(vals.pop()); } }