-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackQueue.java
More file actions
48 lines (40 loc) · 1.22 KB
/
StackQueue.java
File metadata and controls
48 lines (40 loc) · 1.22 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
package stackqueue;
import java.util.Stack;
/**
* @Classname StackQueue
* @Description 用两个栈,实现队列的从队尾插入元素offer()
* 和从队头抛出元素poll()
* @Date 2019/7/2 21:26
* @Created by xww
*/
public class StackQueue<T> {
private Stack<T> stack1 = new Stack<>();
private Stack<T> stack2 = new Stack<>();
public void offer(T data){
stack1.push(data);
}
public T poll(){
if(!stack2.isEmpty()){
return stack2.pop();
}else if(!stack1.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
return null;
}
public static void main(String[] args){
StackQueue<Integer> myQueue = new StackQueue<>();
System.out.println(myQueue.poll());
myQueue.offer(1);
myQueue.offer(2);
myQueue.offer(3);
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
myQueue.offer(4);
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
}
}