-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path232.implement-queue-using-stacks.java
More file actions
65 lines (52 loc) · 1.79 KB
/
232.implement-queue-using-stacks.java
File metadata and controls
65 lines (52 loc) · 1.79 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
58
59
60
61
62
63
64
/*
* @lc app=leetcode id=232 lang=java
*
* [232] Implement Queue using Stacks
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素,不返回
top() -- 仅限c++,java内没有
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
*/
// @lc code=start
class MyQueue {
Stack<Integer> stackIn; //声明变量,没有实际的对象(declaration of a variable)
Stack<Integer> stackOut;
//initialize the data structurea here, stackIn and stackOut
public MyQueue() {
stackIn = new Stack<>(); //allocates an object and make stackIn reference that object
stackOut = new Stack<>();
}
//push element x to the back of queue;
public void push(int x) {
stackIn.push(x);
}
//remove the element from the front of queue and return that element.
public int pop() {
// check while stackOut is empty, move all elements from stackIn to stackOut
if(stackOut.empty()) {
while(!stackIn.empty()) {
stackOut.push(stackIn.pop());
}
}
return stackOut.pop();
}
//Get the front element(只查询数值,不弹出,所以还需要借助push来放回去)
public int peek() {
int res=this.pop(); //这里直接调用同一个类下面的pop函数(This directly calls the pop function from the same class.)
stackOut.push(res);
return res;
}
public boolean empty() {
return stackIn.empty() && stackOut.empty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
// @lc code=end