Implement Stack using Two Queues

后端 未结 23 759
感情败类
感情败类 2020-11-28 17:05

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

Given two queues with their sta

23条回答
  •  萌比男神i
    2020-11-28 17:51

    Here's my answer - where the 'pop' is inefficient. Seems that all algorithms that come immediately to mind have N complexity, where N is the size of the list: whether you choose to do work on the 'pop' or do work on the 'push'

    The algorithm where lists are traded back and fourth may be better, as a size calculation is not needed, although you still need to loop and compare with empty.

    you can prove this algorithm cannot be written faster than N by noting that the information about the last element in a queue is only available through knowing the size of the queue, and that you must destroy data to get to that element, hence the 2nd queue.

    The only way to make this faster is to not to use queues in the first place.

    from data_structures import queue
    
    class stack(object):
        def __init__(self):
            q1= queue 
            q2= queue #only contains one item at most. a temp var. (bad?)
    
        def push(self, item):
            q1.enque(item) #just stick it in the first queue.
    
        #Pop is inefficient
        def pop(self):
            #'spin' the queues until q1 is ready to pop the right value. 
            for N 0 to self.size-1
                q2.enqueue(q1.dequeue)
                q1.enqueue(q2.dequeue)
            return q1.dequeue()
    
        @property
        def size(self):
            return q1.size + q2.size
    
        @property
        def isempty(self):
            if self.size > 0:
               return True
            else
               return False
    

提交回复
热议问题