The idea is to simulate a queue using two stacks (same as previous posts). I use python list as the underlying data structure for stack and add a "move()" method to simplify code: it moves all elements of the "inStack" to the "outStack" when the "outStack" is empty. Here is the code
class Queue(object): def __init__(self): """ initialize your data structure here. """ self.inStack, self.outStack = ,  def push(self, x): """ :type x: int :rtype: nothing """ self.inStack.append(x) def pop(self): """ :rtype: nothing """ self.move() self.outStack.pop() def peek(self): """ :rtype: int """ self.move() return self.outStack[-1] def empty(self): """ :rtype: bool """ return (not self.inStack) and (not self.outStack) def move(self): """ :rtype nothing """ if not self.outStack: while self.inStack: self.outStack.append(self.inStack.pop())
push() you should not use
append() since it is not a standard operation of stack. You should use
push to top instead.
move() like this?:
def move(self): while self.inStack: self.outStack.append(self.inStack.pop())
I agree to what @ keidoubleyoucee says here , and i m surprised at the number of downvotes. May be we are missing something , but I would agree that append() shouldn't be used here - insert(0,x) would be the right choice of operation.
Maybe instead of defining a new function 'move', we could also use 'self.outStack.reverse()' which makes the code seem a bit simpler... Just a suggestion... Time/space complexity not so different
append() do the same thing if we view list as stacks' underlying structure. To do it better we should define a stack class to provide the "standard operation" strictly. However, the insert(0, x) is not the standard op either
@hotea I have the same doubt. I also think it should be what you wrote, but it turns out to be wrong. Do you figure out why?
@hotea Never mind my question. I figured it out.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.