sdu_2017_XY 2018-12-06 03:32 采纳率: 0%
浏览 1074
已采纳

C++中关于堆栈操作的问题

这是我在做将堆栈升序排序的时候遇到的问题,请教一下为什么第二个Print()函数不输出结果。

#include <iostream>
#include <stack>
using namespace std;
void StackSort(stack<int>& s){
    if(s.empty()||s.size()==1)
        return;
    stack<int> tmpStack;
    int first=s.top();
    tmpStack.push(first);
    s.pop();
    while(!s.empty()){
        int top=s.top();
        s.pop();

        while(!tmpStack.empty()&&top>tmpStack.top()){
            int tmp=tmpStack.top();
            tmpStack.pop();
            s.push(tmp);
        }
        tmpStack.push(top);
    }
    while(!tmpStack.empty()){
        int tmpFirst=tmpStack.top();
        tmpStack.pop();
        s.push(tmpFirst);
    }
}
void Print(stack<int>& s){
    while(!s.empty()){
        cout<<s.top();
        s.pop();
    }
}
int main(int argc, char** argv) {
    stack<int> s;
    s.push(5);
    s.push(8);
    s.push(6);
    s.push(2);
    s.push(3);
    Print(s);
    StackSort(s);
    Print(s);
    return 0;
}
  • 写回答

2条回答 默认 最新

  • 白色一大坨 2018-12-06 05:52
    关注

    打印时候不应该用引用,而且建议结尾加个换行,这样更好看一些:

    #include <iostream>
    #include <stack>
    using namespace std;
    void StackSort(stack<int>& s){
        if (s.empty() || s.size() == 1)
            return;
        stack<int> tmpStack;
        int first = s.top();
        tmpStack.push(first);
        s.pop();
        while (!s.empty()){
            int top = s.top();
            s.pop();
    
            while (!tmpStack.empty() && top > tmpStack.top()){
                int tmp = tmpStack.top();
                tmpStack.pop();
                s.push(tmp);
            }
            tmpStack.push(top);
        }
        while (!tmpStack.empty()){
            int tmpFirst = tmpStack.top();
            tmpStack.pop();
            s.push(tmpFirst);
        }
    }
    void Print(stack<int> s){
        while (!s.empty()){
            cout << s.top();
            s.pop();
        }
        cout << endl;
    }
    int main(int argc, char** argv) {
        stack<int> s;
        s.push(5);
        s.push(8);
        s.push(6);
        s.push(2);
        s.push(3);
        Print(s);
        StackSort(s);
        Print(s);
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog