题目::
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, and is 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).
题解:
push永远往空的queue里push,再把不空的加入到之前空的里。
pop和top返回不空的里的第一个元素。
C++版:
class Stack { public: // Push element x onto stack. queue<int> internalA; queue<int> internalB; void push(int x) { if(internalA.empty()) { internalA.push(x); while(!internalB.empty()) { internalA.push(internalB.front()); internalB.pop(); } } else { internalB.push(x); while(!internalA.empty()) { internalB.push(internalA.front()); internalA.pop(); } } } // Removes the element on top of the stack. void pop() { if(internalB.empty()) { internalA.pop(); } else internalB.pop(); } // Get the top element. int top() { if(internalB.empty()) { return internalA.front(); } else return internalB.front(); } // Return whether the stack is empty. bool empty() { return internalA.empty() && internalB.empty(); } };
class MyStack { // Push element x onto stack. Queue<Integer> qA = new LinkedList<>(); Queue<Integer> qB = new LinkedList<>(); public void push(int x) { if(qA.isEmpty()) { qA.add(x); while(!qB.isEmpty()) { qA.add(qB.poll()); } } else { qB.add(x); while(!qA.isEmpty()) { qB.add(qA.poll()); } } } // Removes the element on top of the stack. public void pop() { if(qA.isEmpty()) qB.poll(); else qA.poll(); } // Get the top element. public int top() { if(qA.isEmpty()) return qB.peek(); else return qA.peek(); } // Return whether the stack is empty. public boolean empty() { return qA.isEmpty() && qB.isEmpty(); } }
class Stack: # initialize your data structure here. def __init__(self): self.qA = [] self.qB = [] # @param x, an integer # @return nothing def push(self, x): if not self.qA: self.qA.append(x) while self.qB: self.qA.append(self.qB[0]) self.qB = self.qB[1:] else: self.qB.append(x) while self.qA: self.qB.append(self.qA[0]) self.qA = self.qA[1:] # @return nothing def pop(self): if not self.qA and not self.qB: return if self.qA: self.qA = self.qA[1:] else: self.qB = self.qB[1:] # @return an integer def top(self): if not self.qA: return self.qB[0] else: return self.qA[0] # @return an boolean def empty(self): return not self.qA and not self.qB