代码改变世界

sort a stack

2010-10-03 21:55  wansishuang  阅读(216)  评论(0编辑  收藏  举报

Given a stack S, write a C program to sort the stack (in ascending order).
You are not allowed to make any assumptions about how the stack is implemented; the only functions allowed to be used are: Push, Pop, Top, IsEmpty, IsFull.

 

#include <stack>
#include <iostream>
using namespace std;

template<typename T>
void reverse(stack<T>&s)
{
    if(s.empty()) return;
    T top = s.top();
    s.pop();
    reverse(s);
    push(s, top);
}

template<typename T>
void push(stack<T> &s, int key)
{
    if(s.empty())
    {
        s.push(key);
        return;
    }
    int top = s.top();
    if(top < key)
    {
        s.push(key);
    }   
    else
    {
        s.pop();
        push(s, key);
        s.push(top);
    }
}

int main()
{
    stack<int> s;
    s.push(1);

    s.push(4);
    s.push(5);

    s.push(2);
    s.push(3);

    reverse(s);

    while(!s.empty())
    {
        cout<< s.top() << " ";
        s.pop();
    }
    cout<<endl;
    return 0;
}