// 两个斩实现一个队列
// 两个队列实现一个栈
// 用递归颠倒一个栈
//void reverse(stack<int>&s, int *p)
//{
// int t = s.top();
// s.pop();
// reverse(s, t);
//}
#include <iostream>
using namespace std;
#include <stack>
// 递归 栈元素的排序.最小值在top
void order_stack2(stack<int> &st)
{
if(st.empty())
return;
int tmp = st.top();
st.pop();
if(!st.empty())
{
order_stack2(st);
int tmp2 = st.top();
if (tmp > tmp2)
{
st.pop();
st.push(tmp);
st.push(tmp2);
return;
}
}
st.push(tmp);
}
void order_(stack<int> &st)
{
if (st.empty())
return;
order_stack2(st);
int tmp = st.top();
st.pop();
order_(st);
st.push(tmp);
}
// 非递归 栈元素的排序.
// 利用两个辅助栈.以下排序结果,top()是最小元素。
// p1永远指向第一个辅助栈,p2用来倒腾
void order_stack(stack<int> &st)
{
if (st.empty())
return;
stack<int> st1;
while(! st.empty())
{
int t1 = st.top();
st.pop();
if (st1.empty() || t1 > st1.top())
{
st1.push(t1);
}
else
{
stack<int> st2;
while (!st1.empty() && t1 <= st1.top())
{
st2.push(st1.top());
st1.pop();
}
st1.push(t1);
while (!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
}
}
//
while (!st1.empty())
{
st.push(st1.top());
st1.pop();
}
}
void print_stack(stack<int> s)
{
while(! s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
}
// 递归 栈元素的排序.最小值在top
void zhuanzhi_stack(stack<int> &st)
{
if(st.empty())
return;
int tmp = st.top();
st.pop();
if(!st.empty())
{
zhuanzhi_stack(st);
int tmp2 = st.top();
//if (tmp > tmp2)
//{
st.pop();
st.push(tmp);
st.push(tmp2);
return;
//}
}
st.push(tmp);
}
void zhuanzhi_(stack<int> &st)
{
if (st.empty())
return;
zhuanzhi_stack(st);
int tmp = st.top();
st.pop();
zhuanzhi_(st);
st.push(tmp);
}
int main()
{
stack<int> st;
st.push(10);
st.push(9);
st.push(20);
st.push(0);
st.push(7);
print_stack(st);
order_(st);
cout<<endl;
print_stack(st);
zhuanzhi_(st);
cout<<endl;
print_stack(st);
order_stack(st);
cout<<endl;
print_stack(st);
cout<<endl;
return 0;
}