用队列实现栈
class MyStack:
def __init__(self):
self.length = 0
self.queue1 = []
self.queue2 = []
def push(self, x: int) -> None:
self.queue1.append(x)
self.length += 1
def pop(self) -> int:
for _ in range(self.length-1):
self.queue2.append(self.queue1.pop(0))
t = self.queue1.pop(0)
for _ in range(self.length-1):
self.queue1.append(self.queue2.pop(0))
self.length -= 1
return t
def top(self) -> int:
for _ in range(self.length-1):
self.queue2.append(self.queue1.pop(0))
t = self.queue1.pop(0)
for _ in range(self.length-1):
self.queue1.append(self.queue2.pop(0))
self.queue1.append(t)
return t
def empty(self) -> bool:
return self.length == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
用栈实现队列
class MyQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
self.length = 0
def push(self, x: int) -> None:
self.stack1.append(x)
self.length += 1
def pop(self) -> int:
for _ in range(self.length-1):
self.stack2.append(self.stack1.pop(-1))
t = self.stack1.pop(-1)
for _ in range(self.length-1):
self.stack1.append(self.stack2.pop(-1))
self.length -= 1
return t
def peek(self) -> int:
for _ in range(self.length-1):
self.stack2.append(self.stack1.pop(-1))
t = self.stack1.pop(-1)
self.stack1.append(t)
for _ in range(self.length-1):
self.stack1.append(self.stack2.pop(-1))
return t
def empty(self) -> bool:
return self.length == 0
# 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()
标签:obj,队列,self,length,pop,Python,用栈,def,append
From: https://www.cnblogs.com/DCFV/p/18395946