用一个栈来实现另一个栈的排序

来源:互联网 发布:网络语rbq是什么意思 编辑:程序博客网 时间:2024/04/26 14:19

题目:一个栈中元素的类型为整数,现在将该栈从顶到底按从大到小的顺序排序,只许申请一个栈,除此之外可以申请新的变量,但不能申请额外的数据结构。
算法思路:
将要排序的栈记为sta,申请辅助栈为st_help.保存sta栈顶元素到cur变量,并pop栈顶元素。
1)如果cur小于等于st_help栈顶元素,则将cur压入st_help
2) 如果cur小于st_help 栈顶元素,则将st_help栈顶元素压入sta,并pop st_help栈顶元素,直到cur小于等于st_help栈顶元素,然后压入cur到st_help.
3)重复 1),2),直到将所有的sta为空,然后将st_help中的元素全部压如sta.

#include <iostream>#include <stack>#include <string>using namespace std;void  SortStackByStack(stack<int> & sta){    stack<int> st_help;    int cur;    while(!sta.empty())    {        cur = sta.top();        sta.pop();        if(st_help.empty() || cur <= st_help.top())            st_help.push(cur);        else {            while(!st_help.empty() && (st_help.top() < cur))            {                int temp = st_help.top();                st_help.pop();                sta.push(temp);            }            st_help.push(cur);        }    }//first while    while(!st_help.empty())    {        cur = st_help.top();        st_help.pop();        sta.push(cur);    }}int main(void){    stack<int>  st;    int val;    while(cin>>val)    {        st.push(val);    }    SortStackByStack(st);    while(!st.empty())    {        cout <<st.top()<<" "<<endl;        st.pop();    }    return 0;}
0 0