Implement Queue by Two Stacks

Question

As the title described, you should only use two stacks to implement a queue's actions.

The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

Thoughts

push(): stack1 push elements pop() or top(): if stack2 is empty, push elements on stack1 to stack2. pop() or top() from stack2

Solution

class Queue:

    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, element):
        # write your code here
        self.stack1.append(element)

    def top(self):
        # write your code here
        # return the top element
        if not self.stack2:
            while self.stack1:
                ele = self.stack1.pop()
                self.stack2.append(ele)
        return self.stack2[-1]

    def pop(self):
        # write your code here
        # pop and return the top element
        if not self.stack2:
            while self.stack1:
                ele = self.stack1.pop()
                self.stack2.append(ele)
        return self.stack2.pop()