My Code using two stacks by python


  • 0
    A
    class Queue:
        # initialize your data structure here.
    
    	def __init__(self):
    		self.inStack = []
    		self.outStack = []
        # @param x, an integer
        # @return nothing
    	def push(self, x):
    		self.inStack.append(x)
        # @return nothing
    	def pop(self):
    		if not len(self.outStack) == 0:	
    			self.outStack.pop()
    			return 
    		while not len(self.inStack) == 0:	self.outStack.append(self.inStack.pop())
    		self.outStack.pop()
    	# @return an integer
    	def peek(self):
    		if not len(self.outStack) == 0:	return self.outStack[-1]
    		while not len(self.inStack) == 0:
    			self.outStack.append(self.inStack.pop())
    		return self.outStack[-1]
        # @return an boolean
    	def empty(self):
    		if len(self.outStack) == 0 and len(self.inStack) == 0:	return True
    		else:	return False

  • 0
    H

    pop returns nothing, so should it just be self.outStack.pop() without the return?


  • 0
    A

    Yes, you are right. I ignored the comment of pop


  • 0
    H

    Yeah, that's a good point! It just the comment # @return nothing above the pop function is a little bit confusing.


  • 0
    A

    We fix our views to another :). I rewrite the code and it is accepted.


  • 0

    if not len(self.outStack) == 0:? That's three indirections. Why not just if self.outStack:?


  • 0
    H

    I think this could also apply to while, something like while self.instack:


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.