4. <tag-栈和排序问题>-面试题 03.05. 栈排序 + 面试真题: 对栈进行排序
面试题 03.05. 栈排序
[案例需求]

[思路分析]

[代码实现]
class SortedStack {
Deque<Integer> sortedStack = new LinkedList<>();
Deque<Integer> tempStack = new LinkedList<>();
public SortedStack() {
}
public void push(int val) {
//辅助栈为空, 直接插入到主栈
//辅助栈不为空, 比较后, 把较小的放入辅助栈, 较大的放入主栈(持续的过程!)
if(sortedStack.isEmpty()){
sortedStack.push(val);
}else{
while(sortedStack.peek() < val){
tempStack.push(sortedStack.pop());
if(isEmpty())break;
}
sortedStack.push(val);
while(! tempStack.isEmpty()){
sortedStack.push(tempStack.pop());
}
}
}
public void pop() {
if(!isEmpty())sortedStack.pop();
}
public int peek() {
if(!isEmpty()){
return sortedStack.peek();
}else{
return -1;
}
}
public boolean isEmpty() {
return sortedStack.isEmpty();
}
}
/**
* Your SortedStack object will be instantiated and called as such:
* SortedStack obj = new SortedStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.isEmpty();
*/
面试真题: 对栈进行排序
[案例需求]


[思路分析]

[代码实现]
import java.util.*;
public class test {
public static void main(String[] args) {
//双栈排序int temp = 0;
Stack<Integer> st = new Stack();
st.push(4);
st.push(2);
st.push(1);
st.push(3);
//排序过程. 建立辅助栈, 把主栈出栈一个元素放入辅助栈, 比较主栈栈顶, 1 < 3, 把1出栈, 把3出栈主栈, 1入栈到辅助栈,
Deque<Integer> stack = new LinkedList<>();
if(st.isEmpty())stack.push(st.pop());
//比较主栈和辅助栈的栈顶;
int temp = 0;
while(!st.isEmpty()){
temp = st.pop();
if(stack.isEmpty() || temp > stack.peek()){
stack.push(temp);
}else{
st.push(stack.pop());
stack.push(temp);
}
}
//遍历stack
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
}

浙公网安备 33010602011771号