题解 | #复杂链表的复制#

复杂链表的复制

https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba

import java.util.ArrayList;

public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {

        int ListLength = getNodeLength(pHead, 0);
        if (ListLength == 0) return null;
        ArrayList<RandomListNode> list = ListNodeParseToList(pHead, ListLength, 0);
        ArrayList<RandomListNode> r_list = storageRandomNode(pHead);
        RandomListNode copyNode = null;
        RandomListNode copyNodeHead = null;
        for (int i = 0; i < ListLength; i++) {

            if (i == 0) {
                copyNode = new RandomListNode(list.get(i).label);
                copyNodeHead = copyNode;
            }
            try {
                if ((i + 1) <= ListLength) {
                    copyNode.next = new RandomListNode(list.get(i + 1).label);
                }
            } catch (Exception e) {

            }

            if (r_list.get(i) == null) {
                copyNode.random = null;
            } else {
                copyNode.random = new RandomListNode(r_list.get(i).label);
            }
            copyNode = copyNode.next;
        }
        return copyNodeHead;
    }

    public int getNodeLength(RandomListNode node, int length) {
        while (node != null) {
            node = node.next;
            length++;
        }
        return length;
    }

    public <T> ArrayList<T> ListNodeParseToList(RandomListNode head, int length,
            int start) {
        ArrayList list = new ArrayList();

        while (start != 0) {
            head = head.next;
            start--;
        }

        for (int i = 0; i < length; i++) {
            list.add(head);
            try {
                head = head.next;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public <T> ArrayList<T> storageRandomNode(RandomListNode node) {
        ArrayList list = new ArrayList();
        while (node != null) {
            list.add(node.random);
            node = node.next;
        }
        return list;
    }
}

全部评论
刷了100来道题再回来看,我靠我写的是什么啊
点赞 回复 分享
发布于 2024-02-16 13:19 四川

相关推荐

不愿透露姓名的神秘牛友
07-08 10:39
一个证都没&nbsp;我能填什么
程序员小白条:别人有,你为什么没有,还是这个道理,社会就是比较,竞争,淘汰,你要安逸,那么就要做好淘汰的准备
点赞 评论 收藏
分享
码农索隆:想看offer细节
点赞 评论 收藏
分享
lllllkin:感觉可以精简到一页简历,有些排版感觉不是必须的。 时间线越早的,你自己越熟悉的放前面。描述可以更精简些,一些问题解决感觉可以不用写具体技术栈,卖个关子,等面试官问。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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