-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackQueue07.java
More file actions
46 lines (42 loc) · 1.04 KB
/
StackQueue07.java
File metadata and controls
46 lines (42 loc) · 1.04 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
package offer;
import java.util.*;
/**
* 两个栈实现队列:还有更复杂的考虑
* @author fqx
*
*/
public class StackQueue07 {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
/*
* 全部移到2中
*/
if(stack2.isEmpty()){
while(stack1.size() > 0){
stack2.push(stack1.pop());
}
}
/*
* 如果还空说明没有元素
*/
if(stack2.isEmpty()){
throw new NullPointerException();
}
int head = stack2.pop();
return head;
}
public static void main(String []args){
StackQueue07 s = new StackQueue07();
s.stack1.push(1);
s.stack1.push(2);
s.stack1.push(3);
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
}