0

What are some ways to interleave one queue into another? For example: q1 = 1->2->3 , q2 = a->b->c After interleaving q2 into q1, I'd like to have 1->a->2->b->3->c. All the answers I searched up were about merging them into a NEW queue one by one, instead of altering one queue.

This is what I did, not working at all.

def interleave(q1, q2):
   first = q1.dequeue()
   while q2.size() != 0:
     removed = q2.dequeue()
     first.enqueue(removed)
     first = first.dequeue()

Thanks in advance!

1 Answers1

0

One way to make your code working is like this:

def interleave(q1, q2):
  result = queue.Queue()
  while not q1.empty() or not q2.empty():
    if not q1.empty():
      result.put(q1.get())

    if not q2.empty():
      result.put(q2.get())

  return result

For more information about Python Queue read https://docs.python.org/3.8/library/queue.html

Edgar Domingues
  • 930
  • 1
  • 8
  • 17