class CQueue {
public:
stack<int>stack1,stack2;
CQueue() {
while(!stack1.empty()){
stack1.pop();
}
while(!stack2.empty()){
stack2.pop();
}
}
void appendTail(int value) {
stack1.push(value);
}
int deleteHead() {
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
if(stack2.empty()){
return -1;
}else{
int deleteitem = stack2.top();
stack2.pop();
return deleteitem;
}
}
};
python:
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
self.stack1.append(node)
def pop(self):
if not self.stack2://第二栈为空时
while self.stack1://把第一个栈的值挨个push到第二个栈
self.stack2.append(self.stack1.pop())
//第二栈不为空时,返回第二个栈的top元素
if self.stack2:
return self.stack2.pop()
else:
return -1
go:
type CQueue struct {
inStack,outStack []int
}
func Constructor() CQueue {
return CQueue{}
}
func (this *CQueue) AppendTail(value int) {
this.inStack = append(this.inStack,value)
}
func (this *CQueue) DeleteHead() int {
if(len(this.outStack) == 0){
if(len(this.inStack) == 0){
return -1
}else{
for len(this.inStack) > 0 {
this.outStack = append(this.outStack, this.inStack[len(this.inStack)-1])
this.inStack = this.inStack[:len(this.inStack)-1]
}
}
}
delVal := this.outStack[len(this.outStack)-1]
this.outStack = this.outStack[:len(this.outStack)-1]
return delVal
}