首页 > 试题广场 >

堆栈的使用

[编程题]堆栈的使用
  • 热度指数:19616 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
    堆栈是一种基本的数据结构。堆栈具有两种基本操作方式,push 和 pop。其中 push一个值会将其压入栈顶,而 pop 则会将栈顶的值弹出。现在我们就来验证一下堆栈的使用。(注:本题有多组输入,可以参考该网址:https://www.nowcoder.com/discuss/276

输入描述:
    对于每组测试数据,第一行是一个正整数 n(0 < n <= 10000)。而后的 n 行,每行的第一个字符可能是'P'或者'O'或者'A';如果是'P',后面还会跟着一个整数,表示把这个数据压入堆栈;如果是'O',表示将栈顶的值 pop 出来,如果堆栈中没有元素时,忽略本次操作;如果是'A',表示询问当前栈顶的值,如果当时栈为空,则输出'E'。堆栈开始为空。


输出描述:
    对于每组测试数据,根据其中的命令字符来处理堆栈;并对所有的'A'操作,输出当时栈顶的值,每个占据一行,如果当时栈为空,则输出'E'。
示例1

输入

3
A
P 5
A
4
P 3
P 6
O
A

输出

E
5
3
用栈模拟,注意输入要有空格要用getline(cin,str)
#include<stdio.h>
#include<string>
#include<stack>
#include<iostream>
using namespace std;
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        getchar();
        stack<int> s;
        while(s.size()>1)
            s.pop();
        for(int i=0; i<n; i++)
        {
            string op;
            getline(cin, op);
            if(op[0]=='P')
            {
                int num = 0;
                for(int k=2; k<op.size(); k++)
                    num = num*10+op[k]-'0';
                s.push(num);
            }
            else if(op[0]=='O')
            {
                if(s.size()>=1)
                    s.pop();
            }
            else//A
            {
                if(s.size()>=1)
                    printf("%d\n", s.top());
                else
                    printf("E\n");
            }
        }
        printf("\n");
    }
    return 0;
}


发表于 2019-03-23 14:40:36 回复(0)

python solution:


while True:
    try:
        a=int(input())
        if a==0:break
        stack=[]
        for i in range(a):
            string=input()
            if string.startswith("P"):
                stack.append(string.split()[-1])
            elif string=="A":
                print(stack[-1] if stack else "E")
            else:
                if stack:
                    stack.pop()
        print()

    except:
        break
发表于 2017-10-16 18:40:19 回复(0)
#include<iostream>
(720)#include<stack>
#include<cctype>
using namespace std;
int getnumber(string str,int index)
{
    int number=0;
    while(isdigit(str[index]))
    {
        number=number*10+str[index]-'0';
        index++;
    }
    return number;
}
int main()
{
    int n;
    while(cin>>n)
    {
        if(n==0)
            break;
        getchar();
        stack<int>num;
        while(n--)
        {
            string str;
            getline(cin,str);
            if(str[0]=='P'){
                num.push(getnumber(str,2));
            }else if(str[0]=='O'&&!num.empty()){
                num.pop();
            }else if(str[0]=='A'&&!num.empty()){
                    cout<<num.top()<<endl;
            }else if(str[0]=='A'&&num.empty()){   
                    cout<<"E"<<endl;
            }else 
            {
                continue;
            }
        }
        cout<<endl;
    }
    return 0;
}

发表于 2020-05-06 16:05:49 回复(0)
 
大佬们,可否帮我看看,为啥我的超时呢
#include<bits/stdc++.h>
using namespace std;
int main()
{
    stack<int>s;
    int n,x;
    char a;
    while(scanf("%d",&n)!=EOF&&n!=0)
    {
        while(!s.empty())
            s.pop();
        while(n--)
        {
            scanf("%c",&a);
            if(a=='P')
            {
                scanf("%d",&x);
                s.push(x);
            }
            else if(a=='O')
            {
                if(s.empty()) continue;
                 s.pop();
            }
            else if(a=='A')
            {
                if(s.empty())
                    printf("E\n");
                else printf("%d\n",s.top());
            }
        }
         printf("\n");
    }
    return 0;
    
}


发表于 2020-04-08 10:44:25 回复(2)
#include <bits/stdc++.h>
using namespace std;
stack<int>s;
int main(){
	int n;
    
	while(cin>>n&&n!=0){
		char ch;
		int x;
		while(!s.empty()){
		s.pop();
	}
		while(n--){
			cin>>ch;
			if(ch=='P') {
				cin>>x;
				s.push(x);
			}
			else if(ch=='O'){
                if(s.empty()) continue;//debug:不能漏 
				s.pop();
			}
			else if(ch=='A'){
				if(s.empty()) cout<<"E"<<endl;
				else cout<<s.top()<<endl;
			}
		}
        cout<<endl;//debug:不能漏 
	}
	return 0;
}

发表于 2020-04-07 23:59:31 回复(1)
Java 
import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            int n = scanner.nextInt();
            Stack<Integer> stack = new Stack<>();
            for (int i = 0; i < n; i++) {
                String s = scanner.next();
                //push
                if (s.contains("P")) stack.push(scanner.nextInt());
                //peek
                else if (s.equals("A")){
                    if (!stack.isEmpty()) System.out.println(stack.peek());
                    else System.out.println("E");
                // pop 不需输出
                }else if (s.equals("O")&&!stack.isEmpty()) stack.pop();
            }
            // 题目要求的格式
            System.out.println();
        }
    }
}


发表于 2020-03-19 21:10:11 回复(0)
#include<bits/stdc++.h>
using namespace std;
int main(){
	int n;
	char temp;
	int number;
	while(cin>>n){
		if(n==0) return 0;
		stack<int> S;
		while(n--){
			cin>>temp;
			switch(temp){
				case 'A':
					if(S.empty()==true){
						cout<<"E"<<endl;
					}else{
						cout<<S.top()<<endl;
					}
					break;
				case 'P':
					cin>>number;
					S.push(number);
					break;
				case 'O':
					if(S.empty()!=true)
				    	S.pop();
					break;
				
			}
		}
		cout<<endl;
	}
	return 0;
}

发表于 2020-03-07 14:26:14 回复(0)
#include<bits/stdc++.h>
using namespace std;
stack<int> s;
int main(){
    int n,k;
    while(scanf("%d ",&n)!=EOF  && n!=0){
        while(s.empty()==false)
            s.pop();
        for(int i=0;i<n;i++){
            char c;
            scanf("%c ",&c);
            if(c=='P'){
                scanf("%d ",&k);
                s.push(k);
            }
            else if(c=='O'&&s.empty()==false) s.pop();
            else if(c=='A'&&s.empty()==true) printf("E\n");
            else if(c=='A'&&s.empty()==false){
                k=s.top(); printf("%d\n",k);
            }
        }
        printf("\n");
    }
}
发表于 2019-03-20 10:04:17 回复(0)
没什么说的 按照题目翻译就行了 注意最后有空行
#include<iostream>
#include<stack>
using namespace std;
stack<int> s;
int main(){
    int n,x;
    char c;
    while(cin>>n){
        for(int i=0;i<n;i++){
            cin>>c;
            if(c=='P'){
                cin>>x;
                s.push(x);
            }
            if(c=='O'){
                if(s.empty()==false) s.pop();
            }
            if(c=='A'){
                if(s.empty()==true) cout<<"E"<<endl;
                else cout<<s.top()<<endl;
            }
        }
        cout<<endl;
    }
    return 0;
}

发表于 2019-03-17 21:39:44 回复(1)

数组模拟就可以了

package com.speical.first;

import java.util.Scanner;

/** 
* 堆栈的使用
* 
* 数组模拟即可,因为栈只需要一个栈顶指针即可
* @author special
* @date 2018年2月2日 上午11:53:18
*/
public class Pro177 {
    static int[] nums = new int[10000 + 5];

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        while(input.hasNext()){
            int n = input.nextInt();
            int top = 0;
            while(n-- > 0){
                char ch = input.next().charAt(0);
                if(ch == 'P'){
                    nums[top++] = input.nextInt();
                }else if(ch == 'O'){
                    if(top > 0){
                        nums[--top] = 0;
                    }
                }else if(ch == 'A'){
                    System.out.println(top == 0 ? "E" : nums[top - 1]);
                }
            }
            System.out.println();
        }
    }

}
发表于 2018-02-02 13:56:28 回复(0)
while(num = readline()){
    var count = parseInt(num);
    if (!count) break;
    
    var stack = [];
    for (var i = 0; i < count; i++) {
        var lines = readline().split(' ');
        var op = lines[0];
        var n = lines[1];
        switch (op) {
            case 'A':
                if (stack.length) {
                    print(stack[stack.length - 1]);
                } else {
                    print('E')
                }
                break;
            case 'P':
                stack.push(n);
                break;
            case 'O':
                stack.pop();
                break;
            default:
                break;
        }
    }
    print('');
}

发表于 2017-09-13 22:27:06 回复(2)
#include <cstdio>
#include <stack>
using namespace std;

int main()
{
    //freopen("date.txt", "r", stdin);
    stack<int> S;
    int n, num;
    char c;
    while(scanf("%d", &n) != EOF && n != 0){
        for(int i = 0; i < n; i++){
            c = getchar();
            scanf("%c", &c);
            switch(c){
                case 'A' : if(S.empty()) printf("E\n"); else printf("%d\n", S.top()); break;
                case 'P' : scanf("%d", &num); S.push(num); break;
                case 'O' : if(!S.empty()) S.pop(); break;
            }
        }
        printf("\n");
        while(!S.empty())
            S.pop();
    }
    
    return 0;
}

发表于 2018-02-16 22:37:34 回复(7)
写个垃圾题解,记得吃回车
using namespace std;
#include <cstdio>
#include <stack>
#include <iostream>
int main(){
    int n;
    while(scanf("%d", &n) != EOF and n != 0){
        stack<int> list;
        char op;
        int num;
        while(n--){
        	getchar(); 
            scanf("%c", &op);
            if(op == 'A'){
                if(list.empty())printf("E\n");
                else printf("%d\n", list.top());
            }
            else if(op == 'P'){
                scanf("%d", &num);
                list.push(num);
            }
            else if(op == 'O'){
                if(!list.empty())list.pop();
            }
        }
        printf("\n");
    }
    return 0;
}


发表于 2021-06-22 09:26:32 回复(0)
比较简单,看图说话,就是出栈前记得判空操作
#include <iostream>
#include <stack>
using namespace std;

int main() {
    int n;
    while(cin >> n){
        stack<int> myStack;
        char c;
        int a;
        for(int i = 0; i < n; ++i){
            cin >> c;
            if(c == 'A'){
                if(myStack.empty()) cout << "E" << endl;
                else                cout << myStack.top() << endl;
            }else if(c == 'P'){
                cin >> a;
                myStack.push(a);
            }else if(c == 'O'){
                if(!myStack.empty())    myStack.pop();
            }
        }
    }
    return 0;
}


发表于 2024-02-22 12:08:18 回复(0)
diy stack 模拟
#include <iostream>
using namespace std;
struct myStack{
    int top=0;
    int* arr=new int[10010]{0};
    void pop(){
        if(top>0){
            top--;
        }
    }
    void topElem(){
        if(top>0){
            cout<<arr[top-1]<<endl;
        }else{
            cout<<"E"<<endl;
        }
    }
    void push(int e){
        arr[top++]=e;
    }
};
int main() {
    int n;
    myStack st;
    char op;
    int e;
    while(cin>>n){
        for(int i=0;i<n;i++){
            cin>>op;
            if('A'==op){
                st.topElem();
            }else{
                if('P'==op){
                    cin>>e;
                    st.push(e);
                }else{
                    if('O'==op){
                        st.pop();
                    }
                }
            }
        }
    }
}
// 64 位输出请用 printf("%lld")


发表于 2023-06-10 00:27:46 回复(0)
#include <iostream>
#include <algorithm>
#include <stack>
#include <string>
using namespace std;

stack<int> X;


int main() {
	int n;
	cin >> n;
	char c;
	while (n--)
	{
		cin >> c;
		if (c=='P') {
			int a;
			cin >> a;
			X.push(a);
		}
		else if (c == 'A') {
			if (X.empty())
				cout << 'E'<<endl;
			else
				cout << X.top()<<endl;
		}
		else if (c == 'O') {
			if (! X.empty())
				X.pop();
		}
	}
	return 0;
}

发表于 2023-02-02 18:43:43 回复(0)
#include<bits/stdc++.h>
using namespace std;

int main() {
    int n;
    while(cin>>n) {
        stack<int> Stack;
        while(n--) {
            char a;
            int b;
            cin>>a;
            if(a=='A') {
                if(!Stack.empty()) {
                    cout<<Stack.top()<<endl;
                }    else {
                    cout<<'E'<<endl;
                }
            }
            if(a=='O'&&!Stack.empty()) {
                Stack.pop();
            }
            if(a=='P') {
                cin>>b;
                Stack.push(b);
            }
        }
    }
    return 0;
}
发表于 2022-10-05 21:19:54 回复(1)
#include<stdio.h>
#include<stack>
using namespace std;
stack<int> S;
int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        for(int i=0;i<n;i++){
            char a;
            int b;
            scanf("%c",&a);
            if(a=='P'){
                scanf("%d",&b);
                S.push(b);
            }
            else if(a=='O'){
                if(!S.empty()){
                    S.pop();
                }
            }
            else if(a=='A'){
                if(!S.empty()){
                    printf("%d\n",S.top());
                }
                else printf("E\n");
            }

        }
        printf("\n");
        while(!S.empty())
            S.pop();
    }
    return 0;
}
求各位大佬解答下。一直提示格式不对,感觉完全按照要求额。为啥不对额。

发表于 2019-01-09 10:53:25 回复(6)
大佬们最后一个案例死活过不去,找不到问题
#include<cstdio>
#include<string>
#include<stack>
using namespace std;
int main() {
    int n;
    stack<int>num;
    char s1[20];
    while ((scanf("%d", &n)) != EOF) {
        for (int i = 0; i < n; i++) {
            fgets(s1, 20, stdin);
            string s = s1;
            switch (s[0]) {
                case 'A': {
                        if (num.empty()){
                            printf("E\n");
                        }
                        else {
                            printf("%d\n", num.top());
                        }
                        break;
                    }
                case 'P': {
                        string m;
                        int j = 2;
                        for(int j =2;j<s.size();j++){
                            m.push_back(s[j]);
                        }
                        num.push(stoi(m));
                        break;
                    }
                case 'O': {
                        if (!num.empty()){
                            num.pop();
                        }
                        break;
                    }
                default:break;
            }

        }
    }
}

发表于 2024-03-14 11:50:02 回复(0)
#include <iostream>
#include <stack>
using namespace std;

int main() {
    int n;
    stack<int> s;
    while (cin >>n) { // 注意 while 处理多个 case
        char a;
        int b;
        for(int i=0;i<n;i++){
            cin>>a;
            if(a=='P'){
                cin >>b;
                s.push(b);
            }else if(a=='O'){
                if(!s.empty()){
                    s.pop();
                }
            }else{
                if(s.empty()){
                    cout<<'E'<<endl;
                }else{
                    cout<<s.top()<<endl;
                }
            }
        }
    }
}
// 64 位输出请用 printf("%lld")
发表于 2024-03-06 17:06:56 回复(0)