码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-03-29 21:01:09      阅读:247      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!