复杂链表的复制_JAVA_较难

复杂链表的复制

http://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba

字典存储随机节点法

  • 第一次循环复制新链,并且建立新节点和旧节点的映射存入map中
  • 第二次循环利用map给新链重定向随机节点指向
/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
import java.util.*;
public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        Map<RandomListNode, RandomListNode> map = new HashMap();
        RandomListNode head = new RandomListNode(-1), node = head, pre;
        // 克隆链表
        while(pHead != null) {
            pre = node;
            // 深拷贝节点
            node = new RandomListNode(pHead.label);
            node.random = pHead.random;
            // 连接
            pre.next = node;
            // 存入映射
            map.put(pHead, node);
            pHead = pHead.next;
        }
        // 克隆随机节点
        node = head.next;
        while(node != null) {
            node.random = map.get(node.random);
            node = node.next;
        }
        return head.next;

    }
}

后置节点法

  • 第一个循环创建复制节点,并放置原节点之后
  • 第二个循环给每一个复制节点的随机指针赋值
  • 第三个循环独立出复制节点,并还原链
/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
import java.util.*;
public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        Map<RandomListNode, RandomListNode> map = new HashMap();
        RandomListNode head = new RandomListNode(-1), node = head, pre;
        head.next = pHead;
        // 将克隆节点放到原节点后
        while(pHead != null) {
            node = new RandomListNode(pHead.label);
            node.random = pHead.random;
            node.next = pHead.next;
            pHead.next = node;
            pHead = node.next;
        }

        // 给克隆节点的随机节点赋值
        node = head.next;
        while(node != null) {
            node = node.next;
            node.random = node.random == null ? null : node.random.next;
            node = node.next;
        }

        // 独立出克隆节点
        node = head;
        pHead = head.next;
        while(node.next != null) {
            pre = node;
            node = node.next.next;
            pHead.next = node.next;
            pre.next = node;
            pHead = pHead.next;
        }
        return head.next;
    }
}
全部评论

相关推荐

11-13 10:17
门头沟学院 Java
昨天面美团,jvm,juc问的好深啊,感觉小林coding不太够喔,牛油们有没有什么推荐的八股网站嘛🕒&nbsp;岗位/面试时间👥&nbsp;面试题目🤔&nbsp;面试感受
明天不下雨了:小林Coding:https://xiaolincoding.com/ 全栈哥:https://www.pdai.tech/ Guide哥:https://javaguide.cn/ 秀哥:https://interviewguide.cn/ 沉默王二:https://javabetter.cn/home.html 磊哥:https://www.javacn.site/interview/basic/ 小傅哥:https://bugstack.cn/ 源码哥:https://doocs.github.io/source-code-hunter/#/ 各大厂的公众号技术文章和一些经典的书籍
面试太紧张了怎么办?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务