You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
1.8 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. // The linked list based implementation for the NumberStack ADT
  2. // Your name here
  3. public class LinkedNumberStack implements NumberStack
  4. {
  5. // instance variable
  6. private LNode m_top;
  7. // check whether the stack is empty
  8. public boolean isEmpty()
  9. {
  10. if (m_top == null)
  11. return true;
  12. else
  13. return false;
  14. }
  15. // check whether the stack is full
  16. public boolean isFull()
  17. {
  18. return false;
  19. }
  20. // return the element at the top of the stack
  21. public int top()
  22. {
  23. if (isEmpty())
  24. throw new RuntimeException("top attempted on an empty stack");
  25. else
  26. return m_top.getInfo();
  27. }
  28. // push a value onto the stack
  29. public void push(int v)
  30. {
  31. LNode new_node = new LNode(v);
  32. if (isEmpty()) {
  33. m_top = new_node;
  34. }
  35. else {
  36. new_node.setLink(m_top);
  37. m_top = new_node;
  38. }
  39. }
  40. // remove and return the value at the top of the stack
  41. public int pop()
  42. {
  43. if (isEmpty())
  44. throw new RuntimeException("pop attempted on an empty stack");
  45. else {
  46. int top_val = m_top.getInfo();
  47. LNode prev_node = m_top.getLink();
  48. m_top = prev_node;
  49. return top_val;
  50. }
  51. }
  52. // return the number of elements on the stack
  53. public int size()
  54. {
  55. int current_size = 0;
  56. LNode current_node = m_top;
  57. while (current_node != null) {
  58. current_node = current_node.getLink();
  59. current_size += 1;
  60. }
  61. return current_size;
  62. }
  63. // return a string representation of the stack
  64. @Override
  65. public String toString()
  66. {
  67. String stackContent = "";
  68. LNode current = m_top;
  69. while (current != null)
  70. {
  71. stackContent += current.getInfo() + " ";
  72. current = current.getLink();
  73. }
  74. return stackContent;
  75. }
  76. }