【五月集训】第十三天打卡(双向链表)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

由于双向链表学的不扎实,本次改天重更

1472. 设计浏览器历史记录

题目链接

设计浏览器历史记录

思路

栈解法维护一个栈和一个游标,每次前进后退更改游标

题解

var BrowserHistory = function (homepage) {
    const stack = [homepage];
    let idx = 0;
    return {
        visit: (url) => stack[stack.length = ++idx] = url,
        back: (steps) => stack[idx = Math.max(0, idx - steps)],
        forward: (steps) => stack[idx = Math.min(stack.length - 1, idx + steps)]
    }
};

430. 扁平化多级双向链表

题目链接

扁平化多级双向链表

思路

使用深搜,先查找当前节点有没有子节点,若没有记录链表最后一个节点,若有处理子节点,继续深搜,连接child

题解

function flatten(head: Node | null): Node | null {
    const dfs = (node) => {
        let cur = node;
        // 记录链表的最后一个节点
        let last = null;

        while (cur) {
            let next = cur.next;
            //  如果有子节点,那么首先处理子节点
            if (cur.child) {
                const childLast = dfs(cur.child);

                next = cur.next;
                //  将 node 与 child 相连
                cur.next = cur.child;
                cur.child.prev = cur;

                //  如果 next 不为空,就将 last 与 next 相连
                if (next != null) {
                    childLast.next = next;
                    next.prev = childLast;
                }

                // 将 child 置为空
                cur.child = null;
                last = childLast;
            } else {
                last = cur;
            }
            cur = next;

        }
        return last;
    }

    dfs(head);
    return head;
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值