在栈C ++中推弹出窗口

问题描述

我有一个空的整数堆栈,并用以下格式查询q: 推送x:在堆栈顶部添加x 弹出:移除堆栈顶部 顶部:打印纸叠的顶部 例 输入: 10 按5 最佳 按6 最佳 推3 最佳 流行音乐 最佳 流行音乐 最佳 输出: 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;
    }
}

解决方法

您需要再检查一次条件,以确定堆栈是否为空,例如if(s=="pop" && s.empty() == false),然后才可以弹出。与顶部相似。否则,当堆栈为空时,代码将引发运行时错误。另外,尝试使用#include<bits/stdc++.h>。除此之外,由于根据您的问题有q个查询,因此您需要在cin>>s循环内使用for

,

我看不出编码后的list(map( lambda names: '\t'.join([*names[0].split('\t'),names[1].split('\t')[1]]),zip(first_second,first_last))) 循环的目的。相反,(并在船上听取了旅途的答复),我会这样做:

for

此外,我将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; } } s的声明移到了尽可能接近使用点的位置。