首页 > 编程语言 > 详细

O(1) 空间复杂度逆序栈和排序栈

时间:2015-03-29 20:58:09      阅读:210      评论:0      收藏:0      [点我收藏+]

两种操作都是递归实现,汉诺塔思想。

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

void reverse(stack<int> &s)//逆序栈
{
    if(s.size()==0)
        return ;
    int a=s.top();
    s.pop();
    if(s.size()==0)
    {
        s.push(a);
        return ;
    }
    reverse(s);
    int b=s.top();
    s.pop();
    reverse(s);
    s.push(a);
    reverse(s);
    s.push(b);
}
void Sort(stack<int>&s)//栈顶放大元素
{
    if(s.size()==0)
        return ;
    int a=s.top();
    s.pop();
    if(s.size()==0)
    {
        s.push(a);
        return;
    }
    Sort(s);
    int b=s.top();
    s.pop();
    if(a<b)
    {
        s.push(a);
        Sort(s);
        s.push(b);
    }
    else
    {
        s.push(b);
        Sort(s);
        s.push(a);
    }
}
int main()
{
    stack<int>s;
    for(int i=0;i<10;++i)
        s.push(i);
    reverse(s);
    Sort(s);
    while(!s.empty())
    {
        cout<<s.top()<<endl;
        s.pop();
    }
    getchar();
    return 0;
}

运行结果如下:
技术分享

O(1) 空间复杂度逆序栈和排序栈

原文:http://blog.csdn.net/wdkirchhoff/article/details/44730917

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!