MyStack.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * Linked list implementation of a stack.
  3. *
  4. * Project 3
  5. *
  6. * @author Thomas Flucke tflucke
  7. * @author Lara Luu ljluu
  8. *
  9. * @since 2015/11/02
  10. */
  11. import java.util.EmptyStackException;
  12. public class MyStack<T>
  13. {
  14. /**
  15. * A single node containing an item in the list and a reference to the next node.
  16. */
  17. private class Node
  18. {
  19. public T elm; // contains the data in the node
  20. public Node next; // contains the location of the next linked node
  21. }
  22. private Node first; // contains the first node in the linked list
  23. /**
  24. * Initializes an instance of MyStack
  25. */
  26. public MyStack()
  27. {
  28. first = null;
  29. }
  30. /**
  31. * Places an item at the front of the stack.
  32. * @param item The item to be placed on the stack.
  33. */
  34. public void push(T item)
  35. {
  36. Node newFirst = new Node(); // creates a new node
  37. newFirst.elm = item;
  38. newFirst.next = first;
  39. first = newFirst;
  40. }
  41. /**
  42. * Removes an item from the front of the stack.
  43. * @return The item removed from the stack.
  44. */
  45. public T pop()
  46. {
  47. if (isEmpty())
  48. {
  49. throw new EmptyStackException();
  50. }
  51. T val = first.elm; // stores object to be returned
  52. first = first.next;
  53. return val;
  54. }
  55. /**
  56. * Returns the value at the front of the stack.
  57. * @return The item at the front of the stack.
  58. */
  59. public T peek()
  60. {
  61. if (isEmpty())
  62. {
  63. throw new EmptyStackException();
  64. }
  65. return first.elm;
  66. }
  67. /**
  68. * Checks if there are any items left on the stack.
  69. * @return true if there are no items on the stack, false otherwise.
  70. */
  71. public boolean isEmpty()
  72. {
  73. return first == null;
  74. }
  75. }