面向对象程序设计(基于C++)0201 栈排序

题目

SortUsingStackOnly.cpp
Write a function StackSort to sort a stack in ascending order.
The following are the only functions that should be
used to write this function: push | pop | top | empty.

编写一个函数StackSort来按升序对堆栈进行排序。

只能使用以下函数:push | pop | top | empty。

思路

对栈不熟悉可以先去看看栈的定义
这里粗略的解释就是进电梯。。只有一个出口,先进去的人后出来,后进去的人先出来

而栈排序的本质其实就是插入排序,拿牌举例子
从A中抽一个牌,在B中找到他的位置,然后插入对应的位置即可
在栈上面比较抽象想不出来就举个例子

一开始栈s的数据:7 2 13 6 8
把栈顶的数据放在临时变量中 temp = 8
再开一个新的栈ts

于是有以下情况:
s 7 2 13 6
temp 8
ts

6比8小,放进去
temp 8
s 7 2 13
ts 6

13比8大,那就不放了
临时变量8压进去ts,然后看13比8大,就继续压
遇到2停止压入

然后不同的变量和栈的情况如下:
temp
s 7 2
ts 6 8 13

提出来2放在temp中
把ts掏空
s 7 13 8 6
temp 2
ts

2放进去ts然后压
temp7
ts 2 6 8 13
s
然后把ts比7大的内容放回s中
temp 7
ts 2 6
s 13 8

7放在s中,然后全部放回ts后就排序完成了(排序成功标准是s全空)
temp
ts 2 6 7 8 13
s

代码

#include<iostream>
#include<stack>

using namespace std;

void  StackSort(stack<int>& s);

int main()
{
    stack<int> to_sort;
    int temp;
    while(cin >> temp)
    {
        to_sort.push(temp);
    }
    StackSort(to_sort);
    while(!to_sort.empty())
    {
        cout << to_sort.top()<<" ";
        to_sort.pop();
    }
}

void  StackSort(stack<int>& s)
{
    //s正序,那就让ts的栈顶是最大数
    stack<int> ts;
    int temp;
    while(!s.empty())
    {
        temp = s.top();
        s.pop();
        while(!ts.empty())
        {
            s.push(ts.top());
            ts.pop();
        }

        while(!s.empty() && s.top() < temp)
        {
            ts.push(s.top());
            s.pop();
        }
        ts.push(temp);
        while(!s.empty() && s.top() >= ts.top())
        {
            ts.push(s.top());
            s.pop();
        }
        // if(!s.empty())
        // {
        //     temp = s.top();
        //     s.pop();
        // }
        
        

    }


    while(!ts.empty())
    {
        s.push(ts.top());
        ts.pop();
    }
    
    return ;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值