欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 蓝桥杯学习-11栈

蓝桥杯学习-11栈

2025/3/17 8:13:30 来源:https://blog.csdn.net/weixin_74143480/article/details/146303241  浏览:    关键词:蓝桥杯学习-11栈

11栈

先进后出

例题–蓝桥19877

用数组来设置栈

1.向栈顶插入元素--top位置标记元素
2.删除栈顶元素--top指针减减
3.输出栈顶元素--输出top位置元素

使用arraylist

import java.util.ArrayList;
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc=new Scanner(System.in);ArrayList<Integer> array=new ArrayList<>();int m=sc.nextInt();for (int i = 0; i < m; i++){String str=sc.next();switch (str){case "push":int x=sc.nextInt();array.add(x);break;case "pop":if (array.size()==0){break;}else {array.remove(array.size()-1);}break;case "empty":if (array.size()==0){System.out.println("YES");}else {System.out.println("NO");}break;case "query":if (array.size()==0){System.out.println("empty");}else {System.out.println(array.get(array.size()-1));}break;default:System.out.println("error");}}}}

使用数组

import java.io.*;
import java.util.*;
import java.math.BigInteger;public class Main {static int N = (int)(1e5+10);static int[] stk = new int[N];static int top = 0;static void push(int x) {stk[++top] = x;}static void pop() {if(isEmpty()) return;top--;}static boolean isEmpty() {return top==0;}static void query() {if(isEmpty()) out.println("empty");else out.println(stk[top]);}static void solve() {int m = in.nextInt();while(m-->0) {String op = in.next();if(op.equals("push")) {int x = in.nextInt();push(x);}else if(op.equals("pop")) {pop();}else if(op.equals("empty")) {out.println(isEmpty()?"YES":"NO");}else {query();}}}public static void main(String[] args) {solve();out.flush();}static FastReader in = new FastReader();static PrintWriter out = new PrintWriter(System.out);static class FastReader {static BufferedReader br;static StringTokenizer st;FastReader() {br = new BufferedReader(new InputStreamReader(System.in));}String next() {String str = "";while(st==null||!st.hasMoreElements()) {try {str = br.readLine();}catch(IOException e) {throw new RuntimeException(e);}st = new StringTokenizer(str);}return st.nextToken();}int nextInt() {return Integer.parseInt(next());}double nextDouble() {return Double.parseDouble(next());}long nextLong() {return Long.parseLong(next());}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词