Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Stack {
- private Node last;
- public void push(Integer value) {
- if (last == null) {
- last = new Node(value, null, value);
- }
- else {
- Node node = new Node(value, last, (value != null) ?
- (last.value != null ? Math.max(value, last.value) : value) : last.value);
- last = node;
- }
- }
- public Integer pop() { // get should return the value, not the node
- if (last == null)
- throw new IllegalStateException();
- Node node = last;
- last = last.next;
- return node.value;
- }
- public Integer top() {
- if (last == null)
- throw new IllegalStateException();
- return last.value;
- }
- public boolean empty() {
- return last == null;
- }
- public Optional<Integer> max() { // const
- return Optional.ofNullable(last).map(Node::getMax);
- }
- static class Node {
- public Integer value;
- public Node next;
- public Integer max;
- Node(Integer value, Node next, Integer max) {
- this.value = value;
- this.next = next;
- this.max = max;
- }
- public Integer getMax() {
- return max;
- }
- // getters
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement