package com.daelly.algorithm.stack.reverse;
import java.util.Stack;
public class StackReverse {
public static void stackReverse(Stack<Character> s) {
if(s.isEmpty())return;
char temp1 = s.pop();
stackReverse(s);
if(s.isEmpty()){
s.push(temp1);
return;
}
char temp2 = s.pop();//栈底元素,要翻转到栈顶。先把它拿出来,降规模
stackReverse(s);
s.push(temp1);
stackReverse(s);
s.push(temp2);
}
/**
* 这个是错误的做法
* 要明白递归的思想是,你再递归调用的时候,问题的规模不能加大
* 1处把问题规模变成了n-1
* 但2处有做一次n的规模的递归调用,结果是无限的递归,无法得到输出
* @param s
*/
public static void stackReverseV2(Stack<Character> s) {
if(s.isEmpty())return;
char temp1 = s.pop();
stackReverse(s);//1
stackReverse(s);
s.push(temp1);
stackReverse(s);//2
}
public static void main(String[] args) {
Stack<Character> s = new Stack<>();
for(int i=0;i<10;i++) {
s.push((char)('a'+i));
}
displayStack(s);
stackReverse(s);
displayStack(s);
}
public static void displayStack(Stack<Character> s) {
Stack<Character> ss = new Stack<>();
while(!s.isEmpty()) {
char ch = s.pop();
ss.push(ch);
System.out.print(ch);
System.out.print("<-");
}
while(!ss.isEmpty()) {
s.push(ss.pop());
}
System.out.println();
}
}
栈的反转
最新推荐文章于 2021-03-15 23:53:23 发布