Zigzag Iterator

By | January 18, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

This question is from leetcode zigzag iterator.

Given two 1d vectors, implement an iterator to return their elements alternately.

For example, given two 1d vectors:

v1 = [1, 2]
v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].

First solution I gave out only work for 2 lists. I use currItr to indicate the current work iterator.

Second solution is used by a queue or linkedlist for iterators. It works for Zigzag for k iterators. It should guarantee that each iterator in queue’s hasNext() returns true. Then it pop the next value from the tail iterator, and return the value. Add the tail iterator to head if it still hasNext() is true.

check my code on github: solution1, solution2