牛客网链接:
OR33 用递归函数和栈操作逆序栈
import java.util.*;
public class ReverseStack {
public int[] reverseStackRecursively(int[] stack, int top) {
// write code here
Stack tempStack = new Stack(stack, top);
reverseStackRecursively(tempStack);
return tempStack.stack;
}
//写一个方法,用于返回并移除栈底元素
public int getAndRemoveLastElement(Stack stack){
int result = stack.pop();
if(stack.isEmpty()){
return result;
}else{
int last = getAndRemoveLastElement(stack);
stack.push(result);
return last;
}
}
//完成逆序操作
public void reverseStackRecursively(Stack stack){
if(stack.isEmpty()){
return;
}
//取出栈底元素,将其放到栈顶
int i = getAndRemoveLastElement(stack);
//递归地放入栈顶元素
reverseStackRecursively(stack);
stack.push(i);
}
}
//重新写了一个栈结构
class Stack{
public int[] stack;
public int top;
public Stack(int[] stack, int top){
this.stack = stack;
this.top = top;
}
public void push(int val){
stack[top++] = val;
}
public int pop(){
return stack[--top];
}
public boolean isEmpty(){
return top == 0;
}
}