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);
}
相关推荐
belldeep19 分钟前
如何阅读、学习 Tcc (Tiny C Compiler) 源代码?如何解析 Tcc 源代码?
c语言·开发语言
北上ing2 小时前
算法练习:19.JZ29 顺时针打印矩阵
算法·leetcode·矩阵
XiaoyaoCarter3 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
小狗祈祷诗5 小时前
day22-数据结构之 栈&&队列
c语言·数据结构
AI+程序员在路上6 小时前
XML介绍及常用c及c++库
xml·c语言·c++
软行6 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展
How_doyou_do7 小时前
备战菊厂笔试4
python·算法·leetcode
緈福的街口10 小时前
【leetcode】94. 二叉树的中序遍历
算法·leetcode
小刘要努力呀!10 小时前
嵌入式开发学习(第二阶段 C语言基础)
c语言·学习·算法
草莓熊Lotso10 小时前
【C语言字符函数和字符串函数(一)】--字符分类函数,字符转换函数,strlen,strcpy,strcat函数的使用和模拟实现
c语言·开发语言·经验分享·笔记·其他