Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2022-10-14 #77

Open
github-actions bot opened this issue Oct 13, 2022 · 1 comment
Open

2022-10-14 #77

github-actions bot opened this issue Oct 13, 2022 · 1 comment

Comments

@github-actions
Copy link

No description provided.

@gongpeione
Copy link
Contributor

138 Copy List with Random Pointer

/*
 * @lc app=leetcode id=138 lang=typescript
 *
 * [138] Copy List with Random Pointer
 */

// @lc code=start
/**
 * Definition for Node.
 * class Node {
 *     val: number
 *     next: Node | null
 *     random: Node | null
 *     constructor(val?: number, next?: Node, random?: Node) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *         this.random = (random===undefined ? null : random)
 *     }
 * }
 */

function copyRandomList(head: Node | null): Node | null {
    const nodeMap = new Map<Node, Node>();

    let headPointer = head;

    // copy node and store it to a map
    while (headPointer) {
        const copy = new Node(headPointer.val, null, null);
        nodeMap.set(headPointer, copy);
        headPointer = headPointer.next;
    }

    headPointer = head;
    while(headPointer) {
        const copy = nodeMap.get(headPointer);
        const next = nodeMap.get(headPointer.next) || null;
        const random = nodeMap.get(headPointer.random) || null;

        copy.next = next;
        copy.random = random;

        headPointer = headPointer.next;
    }

    return nodeMap.get(head) || null;
};
// @lc code=end

Nickname: Geeku
From vscode-hzfe-algorithms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant