跳到正文

个人记录

U599065 栈练习 题解

xie2870约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
获赞
1

版本

  1. v1当前

题目:U599065 栈练习

C++
#include<iostream>
using namespace std;
const int maxn=1e5+1000;//定义栈的最大容量
int sta[maxn];//用数组模拟栈
int top=0;//栈顶指针(指向下一个可插入位置)
void push(int x){//入栈操作
	sta[top++]=x;//元素放入栈顶并移动指针
}
int pop(){//出栈操作
	return sta[--top];
}
int getTop(){//获取栈顶元素
	return sta[top-1];//返回当前栈顶元素
}
bool isEmpty(){//判断栈是否为空
	return top==0;//检查栈顶指针是否为0
}
int main(){
	int n;
	scanf("%d",&n);//读取操作数量
	int op,x;
	for(int c=1;c<=n;c++){//循环处理每个操作
		scanf("%d",&op);//读取操作类型
		if(op==1){//入栈操作
			scanf("%d",&x);//读取要入栈的值
			push(x);//调用入栈函数
		}
		if(op==2)pop();//出栈操作
		if(op==3)printf("%d\n",getTop());//输出栈顶元素
	}
}
C++
#include<iostream>
#include<stack>
using namespace std;
int main(){
    stack<int> s;
    int n,lin,lin1;
    cin>>n;
    for(int c=1;c<=n;c++){
        cin>>lin;
        if(lin==1){
            cin>>lin1;
            s.push(lin1);
        }
        if(lin==2)s.pop();
        if(lin==3)cout<<s.top()<<endl;
    }
}

如果你对题解有疑问,可以在评论区发布哦!

原文