225. Implement Stack using Queues
225. Implement Stack using Queues
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid.Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
My Solutions:
queue是linkedlist
用两个queue实现的时候,需要用一个top记录最上面的,保证top() 时间复杂度为1
方法1:Two Queues
用q1储存数字。需要pop的时候,用一个q2储存q1 pop的数字,q1只pop到剩下一个数字,这个数字就是需要pop出的数字。
Time: push: O(1), pop: O(n)
class MyStack {
Queue<Integer> q1 = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();
int top;
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
q1.add(x);
top = x;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while(q1.size() > 1) { // 只在q1里留下一个数字,也就是最后加入的数字
top = q1.remove();
q2.add(top);
}
Queue<Integer> temp = q1; // 交换q1, q2
q1 = q2;
q2 = temp;
return q2.remove(); //q2里最后一个数字就是最后加入的数字
}
/** Get the top element. */
public int top() {
return top;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
方法2: Two Queues
Time: push: O(n), pop: O(1)
push:
q2.add(3)
当q1 不为空时,e.g., q1(2,1), 把q2.add(q1.remove()) --> q2(3,2,1),q1为空
temp = q1; q1 = q2; q2 = temp
q1(3,2,1), q2 为空
pop:
q1.remove
class MyStack {
Queue<Integer> q1, q2;
int top;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
top = x;
if (q1.isEmpty()) q1.offer(x);
else {
q2.offer(x);
while (!q1.isEmpty()) {
q2.offer(q1.poll());
}
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
}
public int pop() {
Integer res = q1.poll();
if (!q1.isEmpty()) top = q1.peek();
return res;
}
public int top() {
return top;
}
public boolean empty() {
return q1.isEmpty();
}
}
方法3: One Queue
Time: push: O(n), pop: O(1)
push:
example 1: q1=(1), q1.add(2)
q1变成(1,2). 算出size = q1.size()。 只要size > 1,q1.add(q1.remove()); size--;
q1(1,2) --> (2,1)
example 2: q1=(2,1), q1.add(3)
q1变成(2,1,3). 算出size = q1.size()。 只要size > 1,q1.add(q1.remove()); size--;
q1(2,1,3) --> (1,3,2) --> (3,2,1)
pop: q1.remove
Last updated