-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStack.java
More file actions
57 lines (49 loc) · 1.25 KB
/
ReverseStack.java
File metadata and controls
57 lines (49 loc) · 1.25 KB
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
package algorithm.stack;
import java.util.Stack;
/**
* @Author: ChangXuan
* @Decription: 逆序栈
* @Date: 12:26 2020/6/22
**/
public class ReverseStack {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println("逆序前:");
for (Integer item : stack){
System.out.println(item);
}
reverse(stack);
System.out.println("逆序后:");
for (Integer item : stack){
System.out.println(item);
}
}
/**
* 取出栈底元素
* @param stack 栈
* @return 栈底元素
*/
public static 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 static void reverse(Stack<Integer> stack){
if (stack.isEmpty()){
return;
}
int i = getAndRemoveLastElement(stack);
reverse(stack);
stack.push(i);
}
}