题目
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 ;
}