Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Another solution for Zigzag Iterator - Acceptable?

Syed Ahmed

Dec 2, 2023

class Solution { private Queue<Integer> queueFirst; private Solution(){ queueFirst = new LinkedList<>(); } public Solution(List<Integer> v1, List<Integer> v2) { queueFirst = new LinkedList<>(); boolean toggle = true; int v1Index = 0; int v2Index = 0; while(!(v1Index==v1.size()) || !(v2Index==v2.size())){ if(!(v1Index==v1.size())){ queueFirst.add(v1.get(v1Index++)); } if(!(v2Index==v2.size())){ queueFirst.add(v2.get(v2Index++)); } } } public int next() { if(!queueFirst.isEmpty()){ return queueFirst.poll(); } return -1; } public boolean hasNext() { return !queueFirst.isEmpty(); }

2

0

Comments
Comments
R
reagankm a year ago

I did it this way too.

I looked into it and here are the reasons the course's solution is better:

  1. Flexibility and Extensibility:
    • The course's solution uses iterators, making it easy to extend the logic to handle more than two lists. By simply adding more...

On this page