[LintCode] Flatten Nested List Iterator 壓平嵌套鏈表迭代器

來源:互聯網
上載者:User

標籤:

 

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example
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].

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].

 

LeetCode上的原題,請參見我之前的部落格Flatten Nested List Iterator。但是不太明白的是,那篇部落格中的解法三可以通過LeetCode的OJ,在LintCode上跑就有錯誤,不知道啥原因。

 

解法一:

class NestedIterator {public:    NestedIterator(vector<NestedInteger> &nestedList) {        for (int i = nestedList.size() - 1; i >= 0; --i) {            s.push(nestedList[i]);        }    }    int next() {        NestedInteger t = s.top(); s.pop();        return t.getInteger();    }    bool hasNext() {        while (!s.empty()) {            NestedInteger t = s.top();             if (t.isInteger()) return true;            s.pop();            for (int i = t.getList().size() - 1; i >= 0; --i) {                s.push(t.getList()[i]);            }        }        return false;    }private:    stack<NestedInteger> s;};

 

解法二:

class NestedIterator {public:    NestedIterator(vector<NestedInteger> &nestedList) {        for (auto a : nestedList) {            d.push_back(a);        }    }    int next() {        NestedInteger t = d.front(); d.pop_front();        return t.getInteger();    }    bool hasNext() {        while (!d.empty()) {            NestedInteger t = d.front();            if (t.isInteger()) return true;            d.pop_front();            for (int i = 0; i < t.getList().size(); ++i) {                d.insert(d.begin() + i, t.getList()[i]);            }        }        return false;    }private:    deque<NestedInteger> d;};

 

[LintCode] Flatten Nested List Iterator 壓平嵌套鏈表迭代器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.