Advertisement
Guest User

Untitled

a guest
Oct 30th, 2014
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. public class ArrayStack<E> implements StackADT<E> {
  2.  
  3.  
  4. // field to refer to an array which will hold the stack elements
  5.  
  6. protected E[] S;
  7.  
  8. // index to top element
  9.  
  10. protected int top = -1;
  11.  
  12.  
  13.  
  14. // a constructor
  15.  
  16. public ArrayStack(int cap) {
  17.  
  18. S = (E[]) new Object[cap];
  19.  
  20. // compiler may give warning, but this
  21. // is OK
  22.  
  23. }
  24.  
  25. public ArrayStack() {
  26.  
  27. S = (E[]) new Object[10];
  28. }
  29.  
  30.  
  31.  
  32.  
  33. public int size () {
  34.  
  35. return (top +1);
  36.  
  37. }
  38.  
  39.  
  40.  
  41. public boolean isEmpty() {
  42.  
  43. return (top <0);
  44.  
  45. }
  46.  
  47.  
  48.  
  49. public E pop() throws EmptyStackException {
  50.  
  51. E element;
  52.  
  53. if (isEmpty())
  54.  
  55. throw new EmptyStackException("Empty stack: cannot pop");
  56.  
  57. element = S[top];
  58.  
  59. S[top] = null; // facilitates garbage collection
  60.  
  61. top = top - 1;
  62.  
  63. return element;
  64.  
  65. }
  66.  
  67.  
  68.  
  69. public E top() throws EmptyStackException {
  70.  
  71. if (isEmpty())
  72.  
  73. throw new EmptyStackException("Stack is empty. Cannot obtain an element");
  74.  
  75. return S[top];
  76.  
  77. }
  78.  
  79.  
  80.  
  81. public void push(E element){
  82.  
  83. // include method body
  84. if (size() == top) {
  85. E[] ProvS = (E[]) new Object[S.length*2];
  86.  
  87. for (int i= 0; i<S.length; i++) {
  88. ProvS[i] = S[i];
  89. }
  90. S = ProvS;
  91. ProvS = null;
  92. }
  93. top++;
  94. S[top]=element;
  95.  
  96. }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement