前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >队列和栈面试题(一)— 请编写一个程序,按升序对栈进行排序,要求最多只能使用一个额外的栈存放临时数据

队列和栈面试题(一)— 请编写一个程序,按升序对栈进行排序,要求最多只能使用一个额外的栈存放临时数据

作者头像
大黄大黄大黄
发布2018-09-14 17:58:22
1.2K0
发布2018-09-14 17:58:22
举报

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_35512245/article/details/54849139

题目:请编写一个程序,按升序对栈进行排序,要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。


思路:首先申请一个栈sta来存放数据栈,再申请一个辅助栈help来存放临时数据,然后比较sta弹出的栈顶的值res与help栈顶元素的大小。

当sta栈不为空时:

1、如果help.empty()或者res<=help.top(),那么就把res的值压入help栈中;

2、如果help不为空并且res>help.top(),那么就把help中栈顶的值弹出并压入sta栈,最后把res的值压入help栈中。

具体可看如下过程图:

1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9

示例代码:

代码语言:javascript
复制
#include<iostream>
#include<string>
#include<stack>//pop,top,push
#include<vector>
using namespace std;
class TwoStacks {
public:
    vector<int> twoStacksSort(vector<int> numbers) 
    {
        stack<int> sta;
        for(vector<int>::reverse_iterator riter=numbers.rbegin();riter!=numbers.rend();riter++)
            sta.push(*riter);
        StackSort(sta);
        vector<int> res;
        while(!sta.empty())
        {
            res.push_back(sta.top());
            sta.pop();
        }
        return res;
    }
    void StackSort(stack<int> &sta)
    {
        stack<int> help;
        while(!sta.empty())
        {
            int res=sta.top();
            sta.pop();
            if(help.empty()||res<=help.top())
                help.push(res);
            else
            {
                while(!help.empty()&&res>help.top())
                {
                    sta.push(help.top());
                    help.pop();
                }
                help.push(res);
            }
        }
        while(!help.empty())
        {
            sta.push(help.top());
            help.pop();
        }
    }
};
int main()
{
    int a[5]={1,2,3,4,5};
    TwoStacks A;
    vector<int> arr(a,a+5),res;
    res=A.twoStacksSort(arr);
    for(vector<int>::iterator iter=res.begin();iter!=res.end();iter++)
        cout<<*iter<<" ";
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年02月03日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档