用递归函数和栈逆序一个栈

用递归函数和栈逆序一个栈

http://www.nowcoder.com/questionTerminal/1de82c89cc0e43e9aa6ee8243f4dbefd

import java.util.*;
public class Main{
    public static void main(String args[]){
        Stack<Integer> stack = new Stack<Integer>();

        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        for(int i=0;i < N;i++){
            stack.push(in.nextInt());
        }
        reverse(stack);
    }
    public static int get(Stack<Integer> stack){
        int result = stack.pop();
        if(stack.isEmpty()){
            return result;
        }
        else{
            int last = get(stack);
            stack.push(result);
            return last;
        }
    }
    public static void reverse(Stack<Integer> stack){
       if(stack.isEmpty()){
            return ;
        }
        int num = get(stack);
        reverse(stack);
        stack.push(num);
        System.out.print(stack.peek()+" ");
       
    }      
    
}
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务