LoganBlackisle

NodeStack

Jun 18th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 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 NodeStack implements StackI {
  9. private Node top;
  10.  
  11. /**
  12. * Constructs an empty stack.
  13. */
  14. public NodeStack() {
  15. top = null;
  16. }
  17.  
  18. /**
  19. * Adds an element to the top of the stack.
  20. *
  21. * @param element the element to add
  22. */
  23. @Override
  24. public void push(Object element) {
  25. Node newNode = new Node();
  26. newNode.data = element;
  27. newNode.next = top;
  28. top = newNode;
  29. }
  30.  
  31. /**
  32. * Removes the element from the top of the stack.
  33. *
  34. * @return the removed element
  35. */
  36. @Override
  37. public Object pop() {
  38. if (top == null) {
  39. throw new NoSuchElementException();
  40. }
  41. Object element = top.data;
  42. top = top.next;
  43. return element;
  44. }
  45.  
  46. /**
  47. * Returns the element from the top of the stack. The stack is unchanged
  48. *
  49. * @return the element from the top of the stack
  50. */
  51. @Override
  52. public Object peek() {
  53. if (top == null) {
  54. throw new NoSuchElementException();
  55. }
  56. return top.data;
  57. }
  58.  
  59. /**
  60. * The number of elements on the stack.
  61. *
  62. * @return the number of elements on the stack
  63. */
  64. @Override
  65. public int size() {
  66. int count = 0;
  67. Node temp = top;
  68. while (temp != null) {
  69. count++;
  70. temp = temp.next;
  71. }
  72. return count;
  73. }
  74.  
  75. /**
  76. * Checks whether this stack is empty.
  77. *
  78. * @return true if the stack is empty
  79. */
  80. @Override
  81. public boolean isEmpty() {
  82. return top == null;
  83. }
  84.  
  85. class Node {
  86. public Object data;
  87. public Node next;
  88. }
  89.  
  90. }
Add Comment
Please, Sign In to add comment