题目
一个栈的元素为整型,现在想将该栈的从栈顶到底按从小到大的顺序排序,只许申请一个栈。除此之外,可以申请新变量,但不能申请额外的数据结构。
难度 ♥
思路
-
选择一个stack.pop()弹出的栈(旧栈)顶元素作为比较值,装入到一个新的栈中
-
用新栈的栈顶值比较旧栈再弹出的值
-
如果新栈的值大于旧栈的值,则将旧栈的值装入到新栈中
-
如果新栈的值小于旧栈的值,则将新栈的值弹出装入到旧栈中
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());
}
```
看完上面的图,到这已经很好理解了,没必要在画图了...
实现
package com.test.desc;
import org.junit.Test;
import java.util.Stack;
/**
* @author lorem
* @date 2018.9.11
*/
public class TestStackDesc {
@Test
public void test(){
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(3);
stack.push(2);
sortStackByStack(stack);
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
public 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());
}
}
}