0%

leetCode-225:Implement Stack using Queues

问题描述

要求用队列实现栈的操作。题目链接:点我

样例输入输出

输入:

[“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
[[], [1], [2], [], [], []]

输出:

[null, null, null, 1, 1, false]

解释:

MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

输入:

[“MyQueue”, “empty”]

[[],[]]

输出:

[null, true]

问题解法

此题比较简单,直接使用队列的特性进行实现即可。代码如下

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
class MyStack {

private Queue<Integer> queue;

private Queue<Integer> queueBak;

private Integer topNum = null;

public MyStack() {
queue = new LinkedList<>();
queueBak = new LinkedList<>();
}

public void push(int x) {
if (queue.size() == 0) {
queueBak.offer(x);
} else {
queue.offer(x);
}

topNum = x;
}

public int pop() {
topNum = null;
if (queue.size() == 0) {
while (queueBak.size() > 1) {
topNum = queueBak.poll();
queue.offer(topNum);
}

return queueBak.poll();
}

while (queue.size() > 1) {
topNum = queue.poll();
queueBak.offer(topNum);
}

return queue.poll();
}

public int top() {
return topNum;
}

public boolean empty() {
return queue.size() == 0 && queueBak.size() == 0;
}
}

/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/