[Title] 03- algorithm using recursion and a stack stack in reverse order

topic

Only the recursive stack and a stack in reverse order.

A stack are sequentially pushed into the top of the stack so 1,2,3,4,5 stack bottom is 5,4,3,2,1, respectively. After this transposed stack from the stack to the bottom of the stack 1,2,3,4,5, i.e. in reverse order to achieve the stack of elements, but can only be implemented by recursion, you can not use other data structures.

Thinking

It requires two recursive function

A recursive function: the bottom of the stack and the return stack element stack removed

/**
     * @Desc 获取栈底元素返回并移除
     * @param stack
     * @return
     */
    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;
        }
    }

If the top of the stack from the stack to the bottom of the stack followed by 3,2,1, the implementation process is as follows:

Recursive Method Two: a stack in reverse order

/**
     * @Desc 逆序一个栈
     * @param stack
     */
    public static void reverse(Stack<Integer> stack) {
        if (stack.isEmpty()) {
            return;
        }
        int i = getAndRemoveLastElement(stack);
        reverse(stack);
        stack.push(i);
    }

achieve

package com.zixin.learn.stackandqueue;

import java.util.Stack;

public class ReverseStackUsingRecursive {

    /**
     * @Desc 逆序一个栈
     * @param stack
     */
    public static void reverse(Stack<Integer> stack) {
        if (stack.isEmpty()) {
            return;
        }
        int i = getAndRemoveLastElement(stack);
        reverse(stack);
        stack.push(i);
    }

    /**
     * @Desc 获取栈底元素返回并移除
     * @param stack
     * @return
     */
    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) {
        Stack<Integer> test = new Stack<Integer>();
        test.push(1);
        test.push(2);
        test.push(3);
        test.push(4);
        test.push(5);
        reverse(test);
        while (!test.isEmpty()) {
            System.out.println(test.pop());
        }

    }

}

Guess you like

Origin www.cnblogs.com/dream-to-pku/p/12425630.html