@[剑指Offer]09两个栈实现队列
09两个栈实现队列
java两种解决方法
我自己写的,将倒序后的元素放回
public int deleteHead() {
if (stack2.isEmpty()){
if (stack1.isEmpty()){
return -1;
}else{
while (!stack1.isEmpty())
stack2.addLast(stack1.removeLast());
return stack2.removeLast();
}
}
else{
return stack2.removeLast();
}}
看大佬的方法写的,不放回,由于队列先进先出,首先将已经倒序后的元素放进stack2,当stack2所有元素(也就是先进的元素)都释放完后,再重新导入stack1的正序元素。
public int deleteHead() {
if (stack1.isEmpty()){
return -1;
}else{
while (!stack1.isEmpty()){
stack2.addLast(stack1.removeLast());
}
int i=stack2.removeLast();
while (!stack2.isEmpty()){
stack1.addLast(stack2.removeLast());
}
return i;
}
}
Python
class CQueue:
def __init__(self):
self.stack1=[]
self.stack2=[]
def appendTail(self, value: int) -> None:
self.stack1.append(value)
# print(self.stack1)
def deleteHead(self) -> int:
if len(self.stack1)>0:
x=len(self.stack1)
for i in range(x):
self.stack2.append(self.stack1.pop())
y=self.stack2.pop()
while self.stack2:
self.stack1.append(self.stack2.pop())
return y
else:
return -1