Looking at some algorithm exercices on the net, I found an interesting one :
How would you implement a FIFO using a LIFO ?
I tried myself but I ended up with only one solution : each time we want the front element of the FIFO, copy the lifo into another lifo (excluding last element, which is the front), get the front element and remove it, then copy back the second LIFO into the first LIFO.
But this is of course horribly slow, it makes a simple loop like this :
for(!myfifo.empty()) {
myfifo.pop();
}
going O(n²) instead of O(n) on a standard implementation of the FIFO.
Of course, LIFO are not made to do FIFO and we won’t certainly have the same complexity by using a “native” FIFO and a fake-FIFO based on a LIFO, but I think there is certainly a way of doing better than O(n²). Has anyone an idea about that ?
Thanks in advance.
You can get amortized time complexity of
O(1)per OP FIFO [queue] using 2 LIFOs [stacks].Assume you have
stack1,stack2:example:
To get real
O(1)[not amortized], it is much more complicated and requires more stacks, have a look at some of the answers in this postEDIT: Complexity analysis:
insert()is trivaiallyO(1)[just pushing it tostack1]push()ed andpop()ed at most twice, once fromstack1and once fromstack2. Since there is no more ops then these, fornelements, we have at most2npush()s and2npop()s, which gives us at most4n * O(1)complexity [since bothpop()andpush()areO(1)], which isO(n)– and we get amortized time of:O(1) * 4n / n = O(1)