简体   繁体   English

将栈顶推入栈顶 c ++

[英]Push pop top in stack c ++

I have an empty stack of integers,and q queries in the following format: Push x: add x in the top of the stack Pop: remove the top of the stack Top: print the top of the stack Example Input: 10 Push 5 Top Push 6 Top Push 3 Top Pop Top Pop Top Output: 5 6 3 6 5 I will put my code in comment because I don't know how to put it here..i know it's extremely wrong but please i need help to improve it我有一个空的整数栈,q 查询格式如下: Push x: add x in the top of the stack Pop: remove the top of the stack Top: print the top of the stack Example Input: 10 Push 5 Top Push 6 Top Push 3 Top Pop Top Pop Top Output: 5 6 3 6 5 我会把我的代码放在评论中,因为我不知道怎么把它放在这里..我知道这是非常错误的,但我需要帮助来改进它


#include <iostream>
#include <stack>

using namespace std;

int main()
{
    stack<int>st;
    int n,a;
    cin>>n;
    string s;
    cin>>s;

    for(int i=0;i<n;i++)
    {
        if(s=="push")
        {
            cin>>a;
            st.push(a);
        }

        if(s=="pop")
            st.pop() ;

        if(s=="top")
            cout<<st.top()<<endl;
    }
}

You need to check one more condition that whether the stack is empty or not, like if(s=="pop" && s.empty() == false) , then only you can pop.您还需要检查一个条件,即堆栈是否为空,例如if(s=="pop" && s.empty() == false) ,那么只有您可以 pop。 Similar thing with top.与顶部类似的东西。 Otherwise code will throw run time error when the stack is empty.否则代码会在堆栈为空时抛出运行时错误。 Also, try using #include<bits/stdc++.h> .另外,尝试使用#include<bits/stdc++.h> Apart from it, since there are q queries as per you question, you need to take cin>>s inside for loop.除此之外,由于根据您的问题有 q 个查询,因此您需要在for循环中使用cin>>s

I don't see the purpose of the for loop, as coded.我没有看到编码的for循环的目的。 Instead, (and taking ajourney's answer on board), I would do:相反,(并在船上接受旅程的回答),我会这样做:

int main()
{
    stack<int>st;

    for ( ; ; )
    {
        string s;
        cin >> s;

        if(s=="push")
        {
            int a;
            cin>>a;
            st.push(a);
        }

        if(s=="pop")
        {
            if (!st.empty ())
                st.pop() ;
            else
                cout << "Stack is empty\n";
        }

        if(s=="top")
        {
            if (!st.empty ())
                cout<<st.top()<<endl;
            else
                cout << "Stack is empty\n";
        }

        if(s=="quit")
            break;
    }
}

Also, I have moved the declarations of s and a to be as close as possible to the point of use.此外,我已将sa的声明移动到尽可能接近使用点的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM