Advertisement
ibragimova_mariam

MAX in Stack

Dec 14th, 2020
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1.  
  2. class Stack {
  3. private Node last;
  4.  
  5. public void push(Integer value) {
  6.  
  7. if (last == null) {
  8. last = new Node(value, null, value);
  9. }
  10. else {
  11. Node node = new Node(value, last, (value != null) ?
  12. (last.value != null ? Math.max(value, last.value) : value) : last.value);
  13. last = node;
  14. }
  15. }
  16.  
  17. public Integer pop() { // get should return the value, not the node
  18.  
  19. if (last == null)
  20. throw new IllegalStateException();
  21.  
  22. Node node = last;
  23. last = last.next;
  24.  
  25. return node.value;
  26. }
  27.  
  28. public Integer top() {
  29.  
  30. if (last == null)
  31. throw new IllegalStateException();
  32.  
  33. return last.value;
  34. }
  35.  
  36. public boolean empty() {
  37. return last == null;
  38. }
  39.  
  40. public Optional<Integer> max() { // const
  41. return Optional.ofNullable(last).map(Node::getMax);
  42. }
  43.  
  44. static class Node {
  45. public Integer value;
  46. public Node next;
  47. public Integer max;
  48.  
  49. Node(Integer value, Node next, Integer max) {
  50. this.value = value;
  51. this.next = next;
  52. this.max = max;
  53. }
  54.  
  55. public Integer getMax() {
  56. return max;
  57. }
  58.  
  59. // getters
  60. }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement