225. Implement Stack using Queues:

关键: Queue中除最后一个元素前面的元素整体搬迁到Queue后面, 这样最后一个元素就到最前面了。

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

Queue<Integer> q;
/** Initialize your data structure here. */
public MyStack() {
q = new LinkedList<>();
}

/** Push element x onto stack. */
public void push(int x) {
q.offer(x);
for (int i = 1; i < q.size(); ++i) {
q.offer(q.poll());
}
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q.poll();
}

/** Get the top element. */
public int top() {
return q.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}

/**
* 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();
*/

232. Implement Queue using Stacks:

关键: 分别是两个stack,相反的操作把LIFO变为了FIFO.

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

Stack<Integer> s1;
Stack<Integer> s2;
/** Initialize your data structure here. */
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}

/** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
}

/** Removes the element from in front of queue and returns that element. */
public int pop() {
peek(); // 作为tmp的s1搬到s2
return s2.pop();
}

/** Get the front element. */
// s2非空,就直接是s2最上面的元素
// s2是空,那么先把FIFO的s1元素全部倒过来放进s2, 再从s2 pop
public int peek() {
if (!s2.empty()) {
return s2.peek();
} else {
while (!s1.empty()) {
s2.push(s1.pop());
}
}
return s2.peek();
}

/** Returns whether the queue is empty. */
public boolean empty() {
return s1.empty() && s2.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();
*/