LoganBlackisle

ArrayStack

Jun 18th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. package prep_27_stack;
  2.  
  3. import java.util.NoSuchElementException;
  4.  
  5. /**
  6. * An implementation of a stack as a sequence of nodes.
  7. */
  8. public class ArrayStack implements StackI {
  9. private Object[] stack;
  10. private int top;
  11.  
  12. /**
  13. * Constructs an empty stack.
  14. */
  15. public ArrayStack(int antal) {
  16. top = -1;
  17. stack = new Object[antal];
  18. }
  19.  
  20. /**
  21. * Adds an element to the top of the stack.
  22. *
  23. * @param element
  24. * the element to add
  25. */
  26. @Override
  27. public void push(Object element) {
  28. growIfNeccassary();
  29. top++;
  30. stack[top] = element;
  31.  
  32. }
  33.  
  34. private void growIfNeccassary() {
  35. if (top + 1 == stack.length) {
  36. Object[] newElements = new Object[stack.length * 2];
  37. for (int i = 0; i < stack.length; i++) {
  38. newElements[i] = stack[i];
  39. }
  40. stack = newElements;
  41. }
  42. }
  43.  
  44. /**
  45. * Removes the element from the top of the stack.
  46. *
  47. * @return the removed element
  48. */
  49. @Override
  50. public Object pop() {
  51. if (top < 0) {
  52. throw new NoSuchElementException();
  53. }
  54. Object element = stack[top];
  55. stack[top] = null;
  56. top--;
  57. return element;
  58. }
  59.  
  60. /**
  61. * Returns the element from the top of the stack. The stack is unchanged
  62. *
  63. * @return the element from the top of the stack
  64. */
  65. @Override
  66. public Object peek() {
  67. if (top < 0) {
  68. throw new NoSuchElementException();
  69. }
  70. return stack[top];
  71. }
  72.  
  73. /**
  74. * The number of elements on the stack.
  75. *
  76. * @return the number of elements on the stack
  77. */
  78. @Override
  79. public int size() {
  80. return top + 1;
  81. }
  82.  
  83. /**
  84. * Checks whether this stack is empty.
  85. *
  86. * @return true if the stack is empty
  87. */
  88. @Override
  89. public boolean isEmpty() {
  90. return top == -1;
  91. }
  92.  
  93. }
Advertisement
Add Comment
Please, Sign In to add comment