Implement Stack using Two Queues

后端 未结 23 823
感情败类
感情败类 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:47

    Here is my solution that works for O(1) in average case. There are two queues: in and out. See pseudocode bellow:

    PUSH(X) = in.enqueue(X)
    
    POP: X =
      if (out.isEmpty and !in.isEmpty)
        DUMP(in, out)
      return out.dequeue
    
    DUMP(A, B) =
      if (!A.isEmpty)
        x = A.dequeue()
        DUMP(A, B)
        B.enqueue(x)
    

提交回复
热议问题