C++
C++的pop()函数没有返回值,Python列表的pop()函数有返回值
class CQueue {
stack<int> stack1;
stack<int> stack2;
public:
CQueue() {}
void appendTail(int value) {
stack1.push(value);
}
int deleteHead() {
if(stack1.empty()) return -1;
while(!stack1.empty()){
int p = stack1.top();
stack1.pop();
stack2.push(p);
}
int res = stack2.top();
stack2.pop();
while(!stack2.empty()){
int n = stack2.top();
stack2.pop();
stack1.push(n);
}
return res;
}
};
Python
在这里不需要将栈2的值再放回栈1,每次删除直接删栈2的末尾就行,如果栈1有内容再把它放到栈2里就行
class CQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def appendTail(self, value: int) -> None:
self.stack1.append(value)
def deleteHead(self) -> int:
if self.stack2: return self.stack2.pop()
if not self.stack1: return -1
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()