Implement Stack using Two Queues

后端 未结 23 724
感情败类
感情败类 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条回答
  •  抹茶落季
    2020-11-28 17:51

    Here is some simple pseudo code, push is O(n), pop / peek is O(1):

    Qpush = Qinstance()
    Qpop = Qinstance()
    
    def stack.push(item):
        Qpush.add(item)
        while Qpop.peek() != null: //transfer Qpop into Qpush
            Qpush.add(Qpop.remove()) 
        swap = Qpush
        Qpush = Qpop
        Qpop = swap
    
    def stack.pop():
        return Qpop.remove()
    
    def stack.peek():
        return Qpop.peek()
    

提交回复
热议问题