-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
48 lines (43 loc) · 1.16 KB
/
MyQueue.java
File metadata and controls
48 lines (43 loc) · 1.16 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 jiuzhang.java.elementary;
import java.util.Stack;
//Implement Queue by Two Stacks
public class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
// do initialization if necessary
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
/*
* @param element: An integer
* @return: nothing
*/
public void push(int element) { //必须理解本质,而不仅仅是顺序步骤操作,本质是倒到有一个stack为空的时候在另一个顶端操作
// write your code here
while (!stack2.empty()) {
stack1.push(stack2.pop());
}
stack1.push(element);
}
/*
* @return: An integer
*/
public int pop() {
// write your code here
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
/*
* @return: An integer
*/
public int top() {
// write your code here
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
return stack2.peek();
}
}