栈和队列(5)——用一个栈实现对另一个栈的排序

要求:

一个栈的元素为整型,现在想将该栈的从栈顶到底按从小到大的顺序排序,只许申请一个栈。

思考:

将要排序的栈记为stack,申请辅助的栈记为help,在stack栈执行pop操作,弹出的元素记为cur,如果cur大于help的栈顶元素,则将cur压入help;如果cur小于help的栈顶元素,则弹出help栈顶元素压入stack直到cur的值大于等于help的栈顶元素。依次运行,直到stack为空之后,把help的栈元素依次压入stack栈里即可。

实现代码:

package algorithm_5;

import java.util.Stack;

public class algorithm_5 {
	public  static void sortStackByStack(Stack<Integer> stack) {
		Stack<Integer> help = new Stack<Integer>();
		while(!stack.isEmpty()){
			int cur = stack.pop();
			while(!help.isEmpty() && help.peek()< cur){
				stack.push(help.pop());
			}
			help.push(cur);
		}
		while (!help.isEmpty()){
			stack.push(help.pop());
		}
	}
	public static void main(String[] args) {
		Stack<Integer> s ;
		s = new Stack<Integer>();
		s.push(1);
		s.push(5);
		s.push(3);
		s.push(4);
		s.push(2);

		sortStackByStack(s);
		while(!s.isEmpty()){
		System.out.println(s.pop());
		}
	}

}
实验结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值