Skip to content

Latest commit

 

History

History
47 lines (35 loc) · 889 Bytes

20211125.md

File metadata and controls

47 lines (35 loc) · 889 Bytes

Algorithm

使用递归函数和栈操作一个逆序栈

Description

一个栈依次压入1,2,3,4,5;那么从栈顶到栈底分别为5,4,3,2,1;将这个栈转置以后,从栈顶到栈底就是1,2,3,4,5,实现了栈的逆序,要求使用递归函数实现上述逆序的过程。

Solution

/**
 * 将栈的栈底元素返回并移除
 */
public 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 void reverse(Stack<Integer> stack){
   if(stack.isEmpty()){
      return;
   }
   int i = getAndRemoveLastElement(stack);
   reverse(stack);
   stack.push(i);
}

Discuss

Review

Tip

Share