Search code examples
pythonpython-3.xqueuefifolifo

Python how to build a LIFO stack using only FIFO queues


I have a very tough question here: how to build a LIFO stack using only FIFO queues ?

So I already have most of the code,but as you can see below ,I don't know how to code the pop function

import queue

class MyLifo:
    def __init__(self):
        self.fifo = queue.Queue();
        self.fifoAux = queue.Queue();

    def isEmpty(self):
        return self.fifo.empty()
    
    def push(self, x):
        self.fifo.put(x)

    def pop(self):
        ### your code here.

### for testing the solution:

lifo = MyLifo()
i=0

while (i<30):
    lifo.push(i)
    i+=1

while (lifo.isEmpty() == False):
    print(lifo.pop())


 
lifo.push(3)
lifo.push(5)
print(lifo.pop())
lifo.push(30)
print(lifo.pop())
print(lifo.pop())
print(lifo.pop())

Any friend can help?


Solution

  • So the better solution is to use queue.LifoQueue(). However, since this is a practice, the following solution have push function with time complexity O(1) and pop function time complexity O(N) that means it itreates through N existing elements in the queue.

    import queue
    
    
    class MyLifo:
        def __init__(self):
            self.fifo = queue.Queue()
    
        def isEmpty(self):
            return self.fifo.empty()
    
        def push(self, x):
            self.fifo.put(x)
    
        def pop(self):
            for _ in range(len(self.fifo.queue) - 1):
                self.push(self.fifo.get())
            return self.fifo.get()
    
    lifo = MyLifo()
    i = 0
    
    while (i < 30):
        lifo.push(i)
        i += 1
    
    while (lifo.isEmpty() == False):
        print(lifo.pop(), end=" ")
        
    

    Output:

    29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0