Stack: Head in, tail out
Queue: Head in, head out
232. Implement Queue using Stacks:
To solve this problem. Implement two stacks. add the value into stack_in, when pop, move all the values into stack_out and then pop the last value (firsrt value in stack in). when push, pop, push, and pop. if anyvalue in stack_out, pop thoese values first because they went in first and need to go first.
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:
if self.stack_in or self.stack_out:
return False
return True
225. Implement Stack using Queues
To implemt stack using queue, move all 1 to n-1 elemts to the back of the list. then pop n.
class MyStack:
def __init__(self):
self.queue = deque()
def push(self, x: int) -> None:
self.queue.append(x)
def pop(self) -> int:
if self.empty():
return None
for i in range(len(self.queue)-1):
self.queue.append(self.queue.popleft())
return self.queue.popleft()
def top(self) -> int:
if self.empty() != None:
return self.queue[-1]
else:
return None
def empty(self) -> bool:
print(self.queue)
return not self.queue

被折叠的 条评论
为什么被折叠?



