Q3.6 sort a stack in ascending order

Q:Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.

A: 再利用另外一个栈来模拟插入排序。 sin是原来的栈,sout是用来储存排序后的栈,

将sin.top() 元素保存在一个临时变量tmp里面,同sout中的元素比较,如果大于sout的top元素,那么就压入当前位置,否则将sout的top元素压入sin之中,tmp继续与sout的top比较,直到sout为空。

#include <iostream>
#include <stack> 
using namespace std;

stack<int> sortStack(stack<int> s) {
	stack<int> t;
	if (s.empty()) {
		return t;
	}
	t.push(s.top());
	s.pop();
	while (!s.empty()) {
		int tmp = s.top();
		s.pop();
		while (!t.empty() && t.top() > tmp) {
			s.push(t.top());
			t.pop();
		}
		t.push(tmp);
	}
	return t;
}

int main() {
	int a[5] = {3,5,2,4,1};
	stack<int> s;
	for (int i = 0; i < 5; i++) {
		s.push(a[i]);
	}
	while (!s.empty()) {
		cout<<s.top()<<" ";
		s.pop();
	}
	cout<<endl;
	for (int i = 0; i < 5; i++) {
		s.push(a[i]);
	}
	s = sortStack(s);
	while (!s.empty()) {
		cout<<s.top()<<" ";
		s.pop();
	}
	cout<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值