Mid Coding

Implement an iterator for a nested list (flatten a nested list of integers)?

public class NestedIterator {

private Queue<int> queue;

public NestedIterator(IList<NestedInteger> nestedList) {

queue = new Queue<int>();

Flatten(nestedList);

private void Flatten(IList<NestedInteger> nestedList) {

foreach (var ni in nestedList) {

if (ni.IsInteger()) queue.Enqueue(ni.GetInteger());

else Flatten(ni.GetList());

public bool HasNext() {

return queue.Count > 0;

public int Next() {

return queue.Dequeue();

Note:

NestedInteger is an interface with methods: IsInteger(), GetInteger(),

GetList().

Explanation:

Pre-flatten the nested list into a queue and iterate over it.

Follow on:

More from C# Programming Tutorial

All questions for this course