维护左右两个队列,控制左队列的长度比右队列长,且不超过1 pushFront 往左队列的左边添加元素 pushMiddle 往左队列的右边或者右队列的左边添加元素 其余同理,可以参照代码
class FrontMiddleBackQueue : def __init__ ( self) : self. llist, self. rlist = [ ] , [ ] def pushFront ( self, val: int ) - > None : self. llist. insert( 0 , val) if len ( self. llist) > len ( self. rlist) + 1 : self. rlist. insert( 0 , self. llist. pop( ) ) def pushMiddle ( self, val: int ) - > None : if len ( self. llist) > len ( self. rlist) : self. rlist. insert( 0 , self. llist. pop( ) ) self. llist. append( val) def pushBack ( self, val: int ) - > None : self. rlist. append( val) if len ( self. rlist) > len ( self. llist) : self. llist. append( self. rlist. pop( 0 ) ) def popFront ( self) - > int : if len ( self. llist) == 0 : return - 1 ans = self. llist. pop( 0 ) if len ( self. rlist) > len ( self. llist) : self. llist. append( self. rlist. pop( 0 ) ) return ansdef popMiddle ( self) - > int : if len ( self. llist) == 0 : return - 1 ans = self. llist. pop( ) if len ( self. rlist) > len ( self. llist) : self. llist. append( self. rlist. pop( 0 ) ) return ansdef popBack ( self) - > int : if len ( self. llist) == 0 : return - 1 if len ( self. rlist) == 0 : return self. llist. pop( ) ans = self. rlist. pop( ) if len ( self. llist) > len ( self. rlist) + 1 : self. rlist. insert( 0 , self. llist. pop( ) ) return ans