JavaScript / TypeScript for LeetCode (153)

是差点运气,可我一直在努力!

当前进程:

  • 开始时间:2020.6.27
  • 结束时间:undefined

GitHub仓库:https://github.com/Cundefined/JavaScript-or-TypeScript-for-LeetCode

1、题目要求

( 剑指 Offer 35 ) 复杂链表的复制

2、解题思路

利用map字典存储原链表节点和新链表节点的对应关系:
    键为原链表节点,值为新链表节点
注意:1、原链表节点与复制的新链表节点【val值要一样】 -- 复制节点值
     2、新链表节点要把原链表节点的指向关系一同复制过来 -- 复制节点之间关系
       【next、random指向可以通过map存储的关系来获取】

2.1、JavaScript Solution

/**
 * // Definition for a Node.
 * function Node(val, next, random) {
 *    this.val = val;
 *    this.next = next;
 *    this.random = random;
 * };
 */

/**
 * @param {Node} head
 * @return {Node}
 */
var copyRandomList = function (head) {
  const map = new Map();

  let cur = head;

  //遍历原链表,键为原链表节点,值为新链表节点
  while (cur !== null) {
    map.set(cur, new Node(cur.val));
    cur = cur.next;
  }

  //指针移动回到链表头部,重新遍历原链表,复制节点之间关系
  cur = head;
  while (cur !== null) {
    //复制节点之间关系 -- .next  .random
    map.get(cur).next = map.get(cur.next);
    map.get(cur).random = map.get(cur.random);

    cur = cur.next;
  }

  return map.get(head);
};

2.2、Java Solution

/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/
class Solution {
    public Node copyRandomList(Node head) {
        HashMap<Node, Node> map = new HashMap<>();

        Node cur = head;

        //遍历原链表,键为原链表节点,值为新链表节点
        while (cur != null) {
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }

        //指针移动回到链表头部,重新遍历原链表,复制节点之间关系
        cur = head;
        while (cur != null) {
            //复制节点之间关系 -- .next  .random
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
        
            cur = cur.next;
        }

        return map.get(head);


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值