stack逆序和排序

// 两个斩实现一个队列
// 两个队列实现一个栈

// 用递归颠倒一个栈
//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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值