Advertisement
desislava_topuzakova

03. Maximum Element

Sep 16th, 2021
1,114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. package StackAndQueue;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Collections;
  5. import java.util.List;
  6. import java.util.Scanner;
  7.  
  8. public class demo {
  9.     public static void main(String[] args) {
  10.         Scanner scanner = new Scanner(System.in);
  11.         ArrayDeque<Integer> stack = new ArrayDeque<>();
  12.         int n = Integer.parseInt(scanner.nextLine());
  13.  
  14.         for (int count = 1; count <= n; count++) {
  15.             String command = scanner.nextLine();
  16.             //"1 X" -> push x to stack
  17.             //"2" -> pop of stack
  18.             //"3" -> print max element only if stack is not empty
  19.             if (command.equals("2")) {
  20.                 stack.pop();
  21.             } else if (command.equals("3")) {
  22.                 //проверка дали имаме елементи
  23.                 if (stack.size() > 0) {
  24.                     System.out.println(Collections.max(stack));
  25.                 }
  26.             } else {
  27.                 //command = "1 97" .split -> ["1", "97"]
  28.                 int x = Integer.parseInt(command.split("\\s+")[1]);
  29.                 stack.push(x);
  30.             }
  31.         }
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement