Python
class CQueue:
def __init__(self):
self.stack1 = list()
self.stack2 = list()
def appendTail(self, value: int) -> None:
self.stack1.append(value)
def deleteHead(self) -> int:
if len(self.stack2) > 0:
return self.stack2.pop()
if len(self.stack1) == 0:
return -1
while self.stack1:
tmp = self.stack1.pop()
self.stack2.append(tmp)
return self.stack2.pop()
# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()
Java
// 版本1:优化版1
class CQueue {
public Stack<Integer> s1;
public Stack<Integer> s2;
public CQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void appendTail(int value) {
s1.push(value);
}
public int deleteHead() {
if (!s2.isEmpty()) {
return s2.pop();
}
if (s1.size() == 0) {
return -1;
}
while (s1.size() > 0) {
int val = s1.pop();
s2.push(val);
}
return s2.pop();
}
}
// 版本2:代码优化之
class CQueue {
public Stack<Integer> s1;
public Stack<Integer> s2;
public CQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void appendTail(int value) {
s1.push(value);
}
public int deleteHead() {
if (s2.size() > 0) {
return s2.pop();
}
if (s1.size() == 0) {
return -1;
}
while (s1.size() > 0) {
int val = s1.pop();
s2.push(val);
}
return s2.pop();
}
}
##Solution1:
注意栈的基本操作与vector略有不同~
class Solution
{
public:
void push(int node) {
stack1.push(node);//
}
int pop() {
int ele_top=0;
if(!stack2.empty()){//stack2不为空,就删除stack2的栈顶元素
ele_top=stack2.top();//top()返回栈顶元素,但不删除
stack2.pop();//pop()删除栈顶元素,但不返回该值
return ele_top;
}
else{//stack2为空,要把stack1中的元素依次弹出并压入stack2中
int ele_temp=0;
while(!stack1.empty()){
ele_temp=stack1.top();
stack2.push(ele_temp);
stack1.pop();
}
ele_top=stack2.top();//返回栈顶元素,但不删除
stack2.pop();//删除栈顶元素,但不返回该值
return ele_top;
}
}
private:
stack<int> stack1;
stack<int> stack2;
};
#20180830重做
class Solution {
public:
void push(int node) { //元素压入stack1中
stack1.push(node);
return;
}
int pop() {
if(stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
int temp = stack2.top();
stack2.pop();
return temp;
}
private:
stack<int> stack1;
stack<int> stack2;
};