仅用递归和栈操作逆序一个栈

  思路就是:每次从利用递归,从栈中取出栈底元素,然后将其他元素按原来的顺序压入栈中即可。

import java.util.Stack;
import java.util.Scanner;

public class Main {
    public static int getAndRemoveLastElement(Stack<Integer> stack) {
        int result = stack.pop();
        if (stack.isEmpty()) {
            return result;
        } else {
            int last = getAndRemoveLastElement(stack);
            stack.push(result);
            return last;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        Stack<Integer> stack = new Stack<>();
        int[] nums = new int[num];
        for (int i = 0; i < num; i++) {
            nums[i] = sc.nextInt();
        }

        for (int i = num - 1; i>= 0; i--){
            stack.push(nums[i]);
        }

        for (int i = 0; i < num; i++) {
            int result = getAndRemoveLastElement(stack);
            System.out.print(result + " ");
        }
    }
}

  这里增加了reverse函数,真正达到了逆序栈的效果,这里调用了之前的getAndRemoveLastElement函数。

import java.util.Stack;
import java.util.Scanner;

public class Main{
    public static int getAndRemoveElement(Stack<Integer> stack){
        int result = stack.pop();
        if (stack.isEmpty()) {
            return result;
        } else {
            int last = getAndRemoveElement(stack);
            stack.push(result);
            return last;
        }
    }
    public static void reverse(Stack<Integer> stack){
        if (stack.isEmpty()) {
            return;
        }
        int i = getAndRemoveElement(stack);
        reverse(stack);
        stack.push(i);
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int elementNum = sc.nextInt();
        Stack<Integer> stack = new Stack<>();
        int[] element = new int[elementNum];
        for (int i = 0; i < elementNum; i++) {
            element[i] = sc.nextInt();
        }
        for (int i = elementNum - 1; i >= 0; i--) {
            stack.push(element[i]);
        }
        reverse(stack);
        while(!stack.isEmpty()){
            System.out.print(stack.pop() + " ");
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值