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

复杂链表的复制

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 四川

相关推荐

在看数据的傻狍子很忙碌:学生思维好重,而心很急,自己想想真的能直接做有难度的东西吗?任何错误都是需要人担责的,你实习生可以跑路,你的同事领导呢
点赞 评论 收藏
分享
ALEX_BLX:虽然说聊天记录不可信,不过这个趋势确实如此但我觉得也要想到一点就是卷后端的人里真正有“料”的人又有多少,我说的这个料都不是说一定要到大佬那种级别,而是就一个正常的水平。即使是现在也有很多人是跟风转码的,2-3个月速成后端技术栈的人数不胜数,但今时不同往日没可能靠速成进大厂了。这种情况就跟考研一样,你能上考场就已经打败一半的人了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务