栈与队列一
思路:对于使用栈实现队列的话,必须使用两个共同来维护使得每次都能先进先出!
class MyQueue:
def __init__(self):
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
self.stack_in.append(x)
def pop(self) -> int:
if self.empty():
return None
if self.stack_out:
return self.stack_out.pop()
else:
for i in range(len(self.stack_in)):
self.stack_out.append(self.stack_in.pop())
return self.stack_out.pop()
def peek(self) -> int:
ans = self.pop()
self.stack_out.append(ans)
return ans
def empty(self) -> bool:
return not (self.stack_in or self.stack_out)
思路:这个比较简单了,简单维护一个队里就可以了!
class MyStack:
def __init__(self):
self.queue = []
def push(self, x: int) -> None:
self.queue.append(x)
def pop(self) -> int:
if self.empty():
return None
return self.queue.pop()
def top(self) -> int:
asn = self.pop()
self.queue.append(asn)
return asn
def empty(self) -> bool:
return not self.queue