您的位置:首页 > 其它

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

2016-09-28 20:52 281 查看
要求:

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

思考:

将要排序的栈记为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());
}
}

}
实验结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: