fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. class GenericResizingStack<Item> implements Iterable<Item> {
  8. private Item[] s;
  9. private int n = 0;
  10.  
  11. public GenericResizingStack (int capacity) {
  12. // @#$*! generic array creation: s = new Item[capacity]; not allowed!
  13. s = (Item[]) new Object[capacity]; // So ugly cast needed
  14. }
  15.  
  16. public void push (Item item) {
  17. if (n == s.length) resize (2 * s.length);
  18. s [n++] = item;
  19. }
  20.  
  21. public Item pop() {
  22. Item item = s[--n];
  23. s[n] = null;
  24. if (n > 0 && n == s.length/4) resize(s.length/2);
  25. return item;
  26. }
  27.  
  28. private void resize(int capacity) {
  29. Item[] copy = (Item[]) new Object[capacity];
  30. for (int i = 0; i < n; i++) copy[i] = s[i];
  31. s = copy;
  32. }
  33.  
  34. public Iterator<Item> iterator() {
  35. return new ReverseArrayIterator(); // Reverse to print in order of popping
  36. }
  37.  
  38. private class ReverseArrayIterator implements Iterator<Item> {
  39. private int i = n-1;
  40.  
  41. public boolean hasNext() {
  42. return i >=0;
  43. }
  44.  
  45. public Item next() {
  46. if (!hasNext ()) throw new NoSuchElementException();
  47. return s[i--];
  48. }
  49. }
  50. }
  51.  
  52.  
  53. /* Name of the class has to be "Main" only if the class is public. */
  54. public class Main
  55. {
  56. public static void main (String[] args) throws java.lang.Exception
  57. {
  58. GenericResizingStack<String> strStack = new GenericResizingStack<String>(1);
  59. strStack.push("Cat");
  60. strStack.push("Dog");
  61.  
  62. System.out.println("Iterating:");
  63. for (String s : strStack) System.out.println(s);
  64.  
  65. System.out.println("Popping:");
  66. System.out.println(strStack.pop());
  67. System.out.println(strStack.pop());
  68. }
  69. }
Success #stdin #stdout 0.09s 54620KB
stdin
Standard input is empty
stdout
Iterating:
Dog
Cat
Popping:
Dog
Cat