0

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?

William
  • 3,724
  • 9
  • 43
  • 76
  • Is this a practice that you're not using `queue.LifoQueue()` ? What is your time complexity expectation of `pop()` and `put()` functions? – aminrd Feb 25 '22 at 23:37
  • Thank you for your reply ,yes not using it,I have no idea of time complexity expectation,I think any one is ok – William Feb 25 '22 at 23:39

1 Answers1

1

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 
aminrd
  • 4,300
  • 4
  • 23
  • 45