双栈排序

题目描述

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

给定一个int[] numbers(C++中为vector&ltint>),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。

测试样例:

[1,2,3,4,5]
返回:[5,4,3,2,1]
思想:利用插入排序的思想,一个栈是已经排好序的,将另一个栈中的元素不停的插入已经排好序的栈中即可,插入操作需要借助出栈和入栈来实现
class TwoStacks {
public:
	vector<int> twoStacksSort(vector<int> numbers) {

		int n = numbers.size();
		if (n<2)return numbers;
		stack<int> temp;
		stack<int> old;
		for (int i = n-1; i >=0; --i){
			old.push(numbers[i]);
		}
		temp.push(old.top());
		old.pop();
		while (!old.empty()){
			int t = old.top();
			old.pop();
			int count = 0;
			while (!temp.empty()&&t < temp.top()){
				old.push(temp.top());
				temp.pop();
				count++;
			}
			temp.push(t);
			while (count>0){
				temp.push(old.top());
				old.pop();
				count--;
			}
		}
		for (int i = 0; i <n; ++i){
			numbers[i] = temp.top();
			temp.pop();
		}
		return numbers;

	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值