题目描述
翻转(颠倒)栈的所有元素,如输入栈{1,2,3,4,5}。其中,1在栈顶,翻转之后的栈为{5,4,3,2,1},5处在栈顶
解题思路
- 申请额外的队列
- 递归
import java.util.Stack;
public class Test15 {
/**把栈底元素移动到栈顶*/
private static void move_bottom_to_top(Stack<Integer>s){
if(s.empty()){
return;
}
int top1=s.peek();
s.pop();
if(!s.isEmpty()){
//递归处理不包含栈顶元素的子栈
move_bottom_to_top(s);
int top2=s.peek();
s.pop();
//交换栈顶元素与子栈栈顶元素
s.push(top1);
s.push(top2);
}else{
s.push(top1);
}
}
public static void reverse_stack(Stack<Integer>s){
if(s.empty()){
return;
}
//把栈底元素移动到栈顶
move_bottom_to_top(s);
int top=s.peek();
s.pop();
//递归处理子栈
reverse_stack(s);
s.push(top);
}
public static void main(String[] args){
Stack<Integer>s=new Stack<>();
for(int i=1;i<=5;i++){
s.push(i);
}
System.out.print("翻转前出栈顺序:");
while(!s.isEmpty()){
System.out.print(s.peek()+" ");
s.pop();
}
for(int i=1;i<=5;i++){
s.push(i);
}
reverse_stack(s);
System.out.print("\n翻转后出栈顺序:");
while(!s.isEmpty()){
System.out.print(s.peek()+" ");
s.pop();
}
}
}
程序运行结果:
翻转前出栈顺序:5 4 3 2 1
翻转后出栈顺序:1 2 3 4 5
算法性能分析
把栈底元素移动到栈顶操作的时间复杂度为O(N),在翻转过程中对每个子栈都进行了把栈底元素移动到栈顶的操作,因此,时间复杂度为O(N^2)
引申:给栈排序
思路:首先对不包含栈顶元素的子栈进行排序,如果栈顶元素大于子栈的栈顶元素,则交换这两个元素。
import java.util.Stack;
public class Test15_2 {
/**把栈底元素移动到栈顶*/
private static void move_bottom_to_top(Stack<Integer>s){
if(s.empty()){
return;
}
int top1=s.peek();
s.pop();
if(!s.isEmpty()){
//递归处理不包含栈顶元素的子栈
move_bottom_to_top(s);
int top2=s.peek();
if(top1>top2){
s.pop();
s.push(top1);
s.push(top2);
return;
}
}
s.push(top1);
}
public static void sort_stack(Stack<Integer>s){
if(s.empty()){
return;
}
//把栈底元素移动到栈顶
move_bottom_to_top(s);
int top=s.peek();
s.pop();
//递归处理子栈
sort_stack(s);
s.push(top);
}
public static void main(String[] args){
Stack<Integer>s=new Stack<>();
int tmp = -1;
for(int i=1;i<=5;i++){
s.push(i*tmp);
tmp=-tmp;
}
System.out.print("排序前出栈顺序:");
while(!s.isEmpty()){
System.out.print(s.peek()+" ");
s.pop();
}
tmp = -1;
for(int i=1;i<=5;i++){
s.push(i*tmp);
tmp=-tmp;
}
sort_stack(s);
System.out.print("\n排序后出栈顺序:");
while(!s.isEmpty()){
System.out.print(s.peek()+" ");
s.pop();
}
}
}
程序运行结果:
排序前出栈顺序:-5 4 -3 2 -1
排序后出栈顺序:-5 -3 -1 2 4
算法性能分析:时间复杂度O(N^2)