代码随想录算法训练营第十天
232.用栈实现队列
思路
模拟题
代码
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022.11
# @Author : hello algorithm!
# @Note : https://leetcode.cn/problems/implement-queue-using-stacks/description/
class MyQueue:
"""
两个stack实现队列
stack1存入栈元素
stack2存所有队列元素
"""
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.stack_out:
return self.stack_out.pop()
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
return self.stack_out.pop()
def peek(self) -> int:
x = self.pop()
self.stack_out.append(x)
return x
def empty(self) -> bool:
if self.stack_in or self.stack_out:
return False
return True
if __name__ == '__main__':
pass
225.用队列实现栈
思路
queue_in
queue_out用来备份数据
代码
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022.11
# @Author : hello algorithm!
# @Note :
class MyStack:
def __init__(self):
self.queue_in = []
self.queue_out = []
def push(self, x: int) -> None:
self.queue_in.append(x)
def pop(self) -> int:
length_in = len(self.queue_in)
while length_in > 1:
self.queue_out.append(self.queue_in.pop(0))
length_in -= 1
x = self.queue_in.pop(0)
while self.queue_out:
self.queue_in.append(self.queue_out.pop(0))
return x
def top(self) -> int:
return self.queue_in[-1]
def empty(self) -> bool:
if self.queue_in:
return False
return True
if __name__ == '__main__':
myStack = MyStack()
myStack.push(1)
myStack.push(2)
myStack.top()
myStack.pop()
myStack.empty()