模拟栈

题目 模拟栈

image-0769851f

思路分析

原题是c++用数组模拟 这里仅作熟悉api练习

代码实现

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        Stack<Integer> stk=new Stack<Integer>();
        for(int i=0;i<n;i++){
            String op=sc.next();
            if(op.equals("push")){
                int x=sc.nextInt();
                stk.push(x);
            }else if(op.equals("pop")){
                stk.pop();
            }else if(op.equals("empty")){
                if(stk.empty()){
                    System.out.println("YES");
                }else{
                    System.out.println("NO");
                }
            }else{
                System.out.println(stk.peek());
            }
        }
    }
}

同类题型

视频讲解


项目分区导航最小的k个数 ⬅️ | 03-模拟栈 | ➡️ 模拟队列