2.思路&code实现一个栈的逆序,但是只能用递归函数的这个栈本身的操作来实现,而不能用自己申请另外的数据结构
思路
1.栈的逆序,如果不借助任何的数据结构,我们只能依靠递归函数来实现。而这个思路也是不容易想到的。首先,我们需要一个get()函数,每次返回栈底的元素,并在栈中移除。递归函数是一个系统调用栈实现。因此很容易实现。第二个函数,reverse函数,将栈中的元素进行逆序。
code
package com.ncst.algo;
import java.util.Stack;
/**
* @author i
* @create 2020/6/29 19:25
* @Description 实现一个栈的逆序,但是只能用递归函数的这个栈本身的操作来实现,而不能用自己申请另外的数据结构
*
* 3 2 1 1 2 3
*/
public class StackResve {
//移除栈底元素并返回。
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 i = get(stack);
reverse(stack);
stack.push(i);
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(3);
stack.push(2);
stack.push(1);
reverse(stack);
while (!stack.isEmpty()){
System.out.print(stack.pop()+"\t");
}
}
}