C++ | Leetcode C++题解之第341题扁平化嵌套列表迭代器

题目:

题解:

cpp 复制代码
class NestedIterator {
private:
    vector<int> vals;
    vector<int>::iterator cur;

    void dfs(const vector<NestedInteger> &nestedList) {
        for (auto &nest : nestedList) {
            if (nest.isInteger()) {
                vals.push_back(nest.getInteger());
            } else {
                dfs(nest.getList());
            }
        }
    }

public:
    NestedIterator(vector<NestedInteger> &nestedList) {
        dfs(nestedList);
        cur = vals.begin();
    }

    int next() {
        return *cur++;
    }

    bool hasNext() {
        return cur != vals.end();
    }
};
相关推荐
程序喵大人1 分钟前
【C++进阶】STL容器与迭代器 - 10 把容器、迭代器和数据流串成一个小程序
开发语言·c++·容器·小程序·迭代器·stl
luj_176822 分钟前
随机性在算法与占卜中的共通原理
c语言·开发语言·c++·经验分享·算法
Lazionr30 分钟前
vector初识——从动态数组到STL核心容器
开发语言·c++
yyds_yyd_1008634 分钟前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
呱呱巨基1 小时前
CMake基础
linux·c++·笔记·学习
lueluelue479 小时前
LeetCode:链表
算法·leetcode·链表
橘子汽水16812 小时前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
Tri_Function13 小时前
动态规划DP1(c++)
c++
清水迎朝阳15 小时前
客户端软件 — 用户统计方案
服务器·c++·客户端·用户统计
Re.不晚16 小时前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展