LeetCode-341 Flatten Nested List Iterator

题目描述

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.

题目大意

给一个链表,链表中有整数以及链表,要求实现两个操作,使得将链表中的所有整数排列起来,不包含任何链表。

示例

E1

Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,1,2,1,1].

E2

Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,4,6].

解题思路

主要是数据结构的选择,根据LeetCode@StefanPochmann的思路,用栈进行保存,分别存储链表的起始位置和终止位置,当栈顶的链表遍历结束时,栈顶元素出栈,进行下一个链表的遍历。

复杂度分析

时间复杂度:O(N)

空间复杂度:O(N)

代码

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *   public:
 *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     bool isInteger() const;
 *
 *     // Return the single integer that this NestedInteger holds, if it holds a single integer
 *     // The result is undefined if this NestedInteger holds a nested list
 *     int getInteger() const;
 *
 *     // Return the nested list that this NestedInteger holds, if it holds a nested list
 *     // The result is undefined if this NestedInteger holds a single integer
 *     const vector<NestedInteger> &getList() const;
 * };
 */
class NestedIterator {
public:
    NestedIterator(vector<NestedInteger> &nestedList) {
        begin.push(nestedList.begin());
        end.push(nestedList.end());
    }

    int next() {
        hasNext();
        return (begin.top()++)->getInteger();
    }
    // 判断并更新栈中元素
    bool hasNext() {
        // 若栈中还有元素
        while(begin.size()) {
            // 如果栈顶的链表已经遍历完,则出栈
            if(begin.top() == end.top()) {
                begin.pop();
                end.pop();
            }
            // 否则继续遍历栈顶链表
            else {
                auto x = begin.top();
                // 若栈顶元素为整数,则返回true
                if(x->isInteger())
                    return true;
                // 否则将链表入栈顶
                begin.top()++;
                begin.push(x->getList().begin());
                end.push(x->getList().end());
            }
        }
        return false;
    }
    
private:
    // 栈中保存了数组的迭代器
    stack<vector<NestedInteger>::iterator> begin, end;
};

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i(nestedList);
 * while (i.hasNext()) cout << i.next();
 */
原文地址:https://www.cnblogs.com/heyn1/p/11213439.html