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

复杂链表的复制

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来道题再回来看,我靠我写的是什么啊
点赞 回复 分享
发布于 02-16 13:19 四川

相关推荐

10-28 14:42
门头沟学院 Java
watermelon1124:因为嵌入式炸了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务