1_5用一个栈实现另一个栈的排序

来源:互联网 发布:jsp javascript 互交 编辑:程序博客网 时间:2024/04/27 11:50

1. 题目: 一个栈中元素的类型为整形,现在想将该栈从顶到底按从大到小的顺序,只需申请一个栈。

2,.思路:我能说最开始我没有读懂题目吗,囧囧囧,语文不好的人不想再解释啦!申请一个辅助栈,存储排序的元素。

3. Answer

#include <stack>#include <iostream>using namespace std;void sortStack(stack<int> &input){stack<int> help;while (!input.empty()){int cur = input.top();input.pop();while (!help.empty() && help.top()<cur){int top = help.top();input.push(top);help.pop();}help.push(cur);}while (!help.empty()){input.push(help.top());help.pop();}}int main(){stack<int> input;for (int i = 8; i >4;i--){input.push(i);}for (int i = 5; i >0 ; i--){input.push(i);}cout<<input.top() << endl;sortStack(input);cout << input.top() << endl;system("pause");return 1;}


0 0
原创粉丝点击