C# solution: tuple, stack, DFS


  • 0
    B
    public class NestedIterator 
    {
        // List and curIndex
        private Stack<Tuple<IList<NestedInteger>, int>> stack;
        private IList<NestedInteger> curList;
        private int curIndex;
    
        public NestedIterator(IList<NestedInteger> nestedList) 
        {
            stack = new Stack<Tuple<IList<NestedInteger>, int>>();
            curList = nestedList;
            curIndex = 0;
        }
    
        public bool HasNext() 
        {
            if (curIndex < curList.Count && curList[curIndex].IsInteger()) return true;
            
            while(curIndex >= curList.Count)
            {
                if (!stack.Any()) return false;
    
                var cur = stack.Pop();
                curList = cur.Item1;
                curIndex = cur.Item2 + 1;
            }
    
            while(!curList[curIndex].IsInteger())
            {
                stack.Push(Tuple.Create(curList, curIndex));
    
                curList = curList[curIndex].GetList();
                curIndex = 0;
    
                if (curIndex >= curList.Count) break;
            }
    
            return HasNext();
        }
    
        public int Next() 
        {
            var result = curList[curIndex];
            curIndex++;
    
            return result.GetInteger();
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.