java-66-用递归颠倒一个栈。例如输入栈{1,2,3,4,5},1在栈顶。颠倒之后的栈为{5,4,3,2,1},5处在栈顶...


import java.util.Stack;

public class ReverseStackRecursive {

/**
* Q 66.颠倒栈。
* 题目:用递归颠倒一个栈。例如输入栈{1,2,3,4,5},1在栈顶。
* 颠倒之后的栈为{5,4,3,2,1},5处在栈顶。
*1. Pop the top element
*2. Reverse the remaining stack
*3. Add the top element to the bottom of the remaining stack
*/
public static void main(String[] args) {
ReverseStackRecursive r=new ReverseStackRecursive();
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<10;i++){
stack.add(i);
}
r.printStack(stack);
r.reverseStack(stack);
r.printStack(stack);
}

public void reverseStack(Stack<Integer> stack){
if(!stack.empty()){
Integer top=stack.pop();
reverseStack(stack);
addToBottom(stack,top);
}
}
public void addToBottom(Stack<Integer> stack,Integer ele){
if(stack.empty()){
stack.push(ele);
}else{
Integer top=stack.pop();
addToBottom(stack,ele);//important
stack.push(top);
}
}
public void printStack(Stack<Integer> stack){
/*
while(!stack.empty()){
System.out.print(stack.pop()+",");
}
*/
//we don't remove the elements in the stack.
for(Integer x:stack){
System.out.print(x+",");
}
System.out.println();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值