没看答案。
利用两个栈
python
class MyQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, x: int) -> None:
if not self.stack1:
self.stack1.append(x)
else:
self.stack2.append(x)
def pop(self) -> int:
x = self.stack1.pop()
if not self.stack1:
while self.stack2:
self.stack1.append(self.stack2.pop())
return x
def peek(self) -> int:
return self.stack1[-1]
def empty(self) -> bool:
return False if self.stack1 else True
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
C++
(剑指offer09)
class CQueue {
private:
stack<int> stk1;
stack<int> stk2;
public:
void appendTail(int value) {
if(stk1.empty()){
stk1.push(value);
}else{
while(!stk1.empty()){
int temp1 = stk1.top();
stk1.pop();
stk2.push(temp1);
}
stk1.push(value);
while(!stk2.empty()){
int temp2 = stk2.top();
stk2.pop();
stk1.push(temp2);
}
}
}
int deleteHead() {
if(stk1.empty()) return -1;
int temp3 = stk1.top();
stk1.pop();
return temp3;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
利用一个栈
python
class MyQueue:
def __init__(self):
self.stack = list()
self.length = 0
def push(self, x: int) -> None:
self.stack.append(x)
self.length += 1
def pop(self) -> int:
num = self.stack.pop(0)
self.length -= 1
return num
def peek(self) -> int:
num = self.stack[0]
return num
def empty(self) -> bool:
return True if self.length == 0 else False
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()