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

题目:

题解:

cpp 复制代码
struct NestedIterator {
    int *vals;
    int size;
    int cur;
};

void dfs(struct NestedIterator *iter, struct NestedInteger **nestedList, int nestedListSize) {
    for (int i = 0; i < nestedListSize; i++) {
        if (NestedIntegerIsInteger(nestedList[i])) {
            (iter->vals)[(iter->size)++] = NestedIntegerGetInteger(nestedList[i]);
        } else {
            dfs(iter, NestedIntegerGetList(nestedList[i]), NestedIntegerGetListSize(nestedList[i]));
        }
    }
}

struct NestedIterator *nestedIterCreate(struct NestedInteger **nestedList, int nestedListSize) {
    struct NestedIterator *ret = malloc(sizeof(struct NestedIterator));
    ret->vals = malloc(sizeof(int) * 20001);
    ret->size = 0;
    ret->cur = 0;
    dfs(ret, nestedList, nestedListSize);
    return ret;
}

bool nestedIterHasNext(struct NestedIterator *iter) {
    return iter->cur != iter->size;
}

int nestedIterNext(struct NestedIterator *iter) {
    return (iter->vals)[(iter->cur)++];
}

void nestedIterFree(struct NestedIterator *iter) {
    free(iter->vals);
    free(iter);
}
相关推荐
dying_man2 小时前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel2 小时前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
草莓熊Lotso2 小时前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
KyollBM2 小时前
【CF】Day75——CF (Div. 2) B (数学 + 贪心) + CF 882 (Div. 2) C (01Trie | 区间最大异或和)
c语言·c++·算法
GGBondlctrl3 小时前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想
CodeOfCC3 小时前
c语言 封装跨平台线程头文件
linux·c语言·windows
momo卡4 小时前
MinGW-w64的安装详细步骤(c_c++的编译器gcc、g++的windows版,win10、win11真实可用)
c语言·c++·windows
超的小宝贝5 小时前
数据结构算法(C语言)
c语言·数据结构·算法
凤年徐7 小时前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表