算法 Java Leetcode

Implement basic operations of a stack using queues.

Question

Implement the following operations of a stack using queues.

  • push(x) —— Push element x onto stack.
  • pop() —— Remove the element on top of the stack.
  • top() —— Get the top element.
  • empty() —— Return whether the stack is empty.

See it on Leetcode

Notes

  1. You must use only standard operations of a queue —— which means only push to back, peek/pop from front, size and is empty operations are valid.
  2. Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque(double-ended que), as long as you use only standard operations of a queue.
  3. You may assume that all operations are valid(eg. no pop or top operations will be called on an empty stack).

Solution

  • java
  • cpp
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
class MyStack {  
private Queue<Integer> q1 = new LinkedList<Integer>();
private Queue<Integer> q2 = new LinkedList<Integer>();

// Push element x onto stack.
public void push(int x) {
if (q1.isEmpty()) {
q1.offer(x);
while (!q2.isEmpty()) q1.offer(q2.poll());
} else {
q2.offer(x);
while (!q1.isEmpty()) q2.offer(q1.poll());
}
}

// Remove the element on top of the stack.
public void pop() {
if (!q1.isEmpty()) q1.poll();
if (!q2.isEmpty()) q2.poll();
}

// Get the top element.
public int top() {
if (!q1.isEmpty()) {
return q1.peek();
} else {
return q2.peek();
}
}

// Return whether the stack is empty.
public boolean empty() {
return q1.isEmpty() && q2.isEmpty();
}
}

Editorial Solution

  • java
  • cpp
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
class MyStack {  
private LinkedList<Integer> q1 = new LinkedList<>();

// Push element x onto stack.
public void push(int x) {
q1.add(x);
int size = q1.size();
while (size > 1) {
q1.add(q1.remove());
size--;
}
}

// Remove the element on top of the stack.
public void pop() {
q1.remove();
}

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

// Return whether the stack is empty.
public boolean empty() {
return q1.isEmpty();
}
}