-
Notifications
You must be signed in to change notification settings - Fork 10
/
ReverseStack.java
65 lines (56 loc) · 1.59 KB
/
ReverseStack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.camnter.basicexercises.stack;
import java.util.Stack;
/**
* 只用递归和栈操作逆序一个栈
* <p/>
* 递归一,将栈底元素取出并从栈内删除
* 递归二,调用递归一,直到栈空,然后全部压栈
*
* @author CaMnter
*/
public class ReverseStack<T> {
/**
* 将栈底元素取出并从栈内删除
* <p/>
* 一直翻到最底部,拿到栈底元素
* 然后层层递归回来的时候又一个一个把过程中的非栈底元素放进去
*
* @param stack stack
* @return T
*/
public T getAndRemoveLastElement(Stack<T> stack) {
T result = stack.pop();
if (stack.isEmpty()) {
return result;
} else {
T last = getAndRemoveLastElement(stack);
stack.push(result);
return last;
}
}
public void reverse(Stack<T> stack) {
if (stack.isEmpty()) {
return;
}
// 拿到栈底元素
T t = getAndRemoveLastElement(stack);
// 递归不断拿栈底元素
reverse(stack);
// 层层递归的栈底元素放入
stack.push(t);
}
public static void main(String[] args) {
ReverseStack<Integer> reverseStack = new ReverseStack<Integer>();
Stack<Integer> stack = new Stack<Integer>();
stack.push(6);
stack.push(5);
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(1);
reverseStack.reverse(stack);
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}