Queue and Stack Getting the max element of a stack

Write a program simulating a stack that can effectively return the current max element. Your program should read a sequence of commands of different types from the standard input.

There are three types of commands:

push v is to add an element (v) to a top of the stack;
pop is to remove the top element of the stack;
max is to return the current max in the stack.
The time complexity of these operations should not depend on the stack size (constant time, O(1)).

Hint: you may use several standard stacks to write a solution.

Input data format

The first line contains the number of commands. Next lines contain one of the following commands: push v, pop, max.

Output data format

The program must output the current max for each command max.
Note, that if your methods have time complexity more than O(1), your solution will not be accepted by timeout restriction.
Report a typo
Sample Input 1:

5
push 2
push 1
max
pop
max
Sample Output 1:

2
2
Sample Input 2:

5
push 1
push 2
max
pop
max
Sample Output 2:

2
1
Sample Input 3:

10
push 2
push 3
push 9
push 7
push 2
max
max
max
pop
max
Sample Output 3:

9
9
9
9

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Deque<Integer> stack = new ArrayDeque<>();
        Deque<Integer> stackMaximum = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            String action = sc.next();
            switch (action) {
                case "push":
                    int num = sc.nextInt();
                    stack.offerLast(num);
                    int max = Math.max(num, stackMaximum.size() == 0 ? num : stackMaximum.peekLast());
                    stackMaximum.offerLast(max);
                    break;
                case "pop":
                    stack.pollLast();
                    stackMaximum.pollLast();
                    break;
                case "max":
                    System.out.println(stackMaximum.peekLast());
                    break;
                default:
                    System.out.println("Something wrong");
                    break;
            }
        }
    }
}



import java.util.*;

class Main {
    public static void main(String[] args) {
        Deque<Integer> stk = new ArrayDeque<>();
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        while (n-- > 0) {
            switch (s.next()) {
                case "push": 
                    int i = s.nextInt();
                    stk.push(stk.isEmpty() || i >= stk.peek() ? i : stk.peek());
                    break;
                case "pop": 
                    stk.pop();
                    break;
                default:
                    System.out.println(stk.peek());
                    break;
            }
        }
    }
}
posted @ 2020-09-28 08:50  longlong6296  阅读(154)  评论(0)    收藏  举报