0

This bit of code is from hackerrank.com.

def pop(self):
    #looks at the top of the queue
    if len(self.stack2) > 0:
        top = self.stack2.pop() 
        self.stack2.append(top)

Can someone please explain why it is popping off the last item in the stack/queue and then just appending it? I thought in queues, it is first in first out. In that case, the "top" item in the queue should be self.stack2.pop(0) ?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • Depends on what the rest of the implementation is doing. You could, for example, implement a queue where you add the new elements the start of a list and read by `pop`ping from the end. – Batman Nov 20 '16 at 22:47

1 Answers1

0

If you are referring to this code:

def peek(self):
    if len(self.stack2) > 0:
        top = self.stack2.pop()
        self.stack2.append(top)
    else:
        while(len(self.stack1) > 1): 
            self.stack2.append(self.stack1.pop())
        top = self.stack1.pop()
        self.stack2.append(top)
    return top

... then the clue is in the name: the two lines in question pop a value off the top of self.stack2, storing it in the variable top, then push it back onto the top of the stack so that the stack remains unchanged, and the value can be returned in the last line of the method. Hence the name peek, as in "take a peek at the top value on the stack without permanently changing anything".

The rest of the code, including the else clause in peek(), is the classic implementation of a two-stack queue, explained in detail here:

https://stackoverflow.com/a/39089983

Community
  • 1
  • 1
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • So why can't we just use top = self.stack2[-1] or something to figure out the top of the stack, instead of the pop and append? –  Nov 21 '16 at 19:21
  • 1
    The [exercise](https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks) is to implement a queue using two [stacks](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)), so the author has attempted to use only the two operations guaranteed to be available for stacks: `push` (called `append` in Python lists) and `pop` (although they arguably cheated a bit by also using `len`). – Zero Piraeus Nov 21 '16 at 20:38