Given a nested list of integers, implement an iterator to flatten it.
Each element was either an integer, or a list--whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]] ,
By calling next repeatedly until hasnext returns FALSE, the order of elements returned by next should be: [1,1,2,1,1] .
Example 2:
Given the list [1,[4,[6]]] ,
By calling next repeatedly until hasnext returns FALSE, the order of elements returned by NEXT should be: [1,4,6] .
Subscribe to see which companies asked this question
Obviously this is a recursive problem, but the topic requires implementation of an iterator, here I think of two methods: 1. Use recursion directly in the constructor to construct the entire sequence, and then return 2. Stack save history, the top of the stack to save the currently printed list and where to print to the list, the first implementation is very smooth, but later submitted to find the test case has an empty list of cases, such as input as [[],[[]], this is troublesome, The way to do this is to save a cache node below is the way to implement it yourself:
#include <stack> #include <vector> #include <assert.h>struct nestedcontext {const vector< nestedinteger>* VEC; size_t pos;}; Class Nestediterator {public:nestediterator (vector<nestedinteger> &nestedlist) {Has_next = true; if (Nestedlist.empty ()) {return; } Nestedcontext ctx = {&nestedlist, 0}; S.push (CTX); } int Next () {return cache_val; } bool _next (int& val) {while (!s.empty ()) {nestedcontext& CTX = S.top (); if (Ctx.vec->at (Ctx.pos). Isinteger ()) {int RV = Ctx.vec->at (ctx.pos++). Getinteger (); if (Ctx.pos >= ctx.vec->size ()) {s.pop (); } val = rv; return true; } else {const vector<nestedinteger>& nestedlist = Ctx.vec->at (ctx.pos++). GetList () ; if (Ctx.pos >= CTX. Vec->size ()) {s.pop (); } if (!nestedlist.empty ()) {Nestedcontext New_ctx = {&nestedlist, 0}; S.push (NEW_CTX); }}} return false; } bool Hasnext () {has_next = _next (cache_val); Return!s.empty () | | Has_next; } stack<nestedcontext> S; BOOL Has_next; int cache_val;};
Leetcode 341. Flatten Nested List Iterator