简体   繁体   中英

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


#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. Similar thing with top. Otherwise code will throw run time error when the stack is empty. Also, try using #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.

I don't see the purpose of the for loop, as coded. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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