理论基础
文章讲解:代码随想录
232.用栈实现队列
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
class MyQueue(object):
def __init__(self):
#set up two stack one for in and one for out
self.stack_in=[]
self.stack_out=[]
def push(self, x):
"""
:type x: int
:rtype: None
"""
#append new value to stack_in
self.stack_in.append(x)
def pop(self):
"""
:rtype: int
"""
#return none if empty.
if self.empty():
return None
#if there is element in stack_out, reomove and print the last element.
if self.stack_out:
return self.stack_out.pop()
#if there is no element in stack_out, move stack_in elements to
#stack_out, then remove and print the last element.
else:
for i in range(len(self.stack_in)-1,-1,-1):
self.stack_out.append(self.stack_in[i])
self.stack_in=[]
return self.stack_out.pop()
def peek(self):
"""
:rtype: int
"""
#return none if empty.
if self.empty():
return None
#if there is element in stack_out, print the last element.
if self.stack_out:
return self.stack_out[-1]
#if there is no element in stack_out, move stack_in elements to
#stack_out, then print the last element.
else:
for i in range(len(self.stack_in)-1,-1,-1):
self.stack_out.append(self.stack_in[i])
self.stack_in=[]
return self.stack_out[-1]
def empty(self):
"""
:rtype: bool
"""
#if there is element in stack_in or stack_out, our boolean should be
#False
return not (self.stack_in or self.stack_out)
225. 用队列实现栈
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
from collections import deque
class MyStack(object):
def __init__(self):
#set up two queue
self.queue_in=deque()
self.queue_out=deque()
def push(self, x):
"""
:type x: int
:rtype: None
"""
#append to queue_in
self.queue_in.append(x)
def pop(self):
"""
:rtype: int
"""
#return none if empty
if self.empty():
return None
#move all element except the last one to the other queue
#pop the last one
for i in range(len(self.queue_in)-1):
self.queue_out.append(self.queue_in.popleft())
self.queue_out,self.queue_in=self.queue_in,self.queue_out
return self.queue_out.popleft()
def top(self):
"""
:rtype: int
"""
#return none if empty
if self.empty():
return None
#return the last one in the queue_in
return self.queue_in[-1]
def empty(self):
"""
:rtype: bool
"""
#check if there is element in queue_in
return not(self.queue_in)
总结:
对于buildin function不够熟悉 要多多运用