Copy List with Random Pointer

Copy List with Random Pointer

问题:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

思路:

  之前看过这道题,所以立马想到了对应的思路,node-->copynode-->node.next-->copynode.next

我的代码:

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null)    return head;
        RandomListNode cur = head;
        while(cur != null)
        {
            RandomListNode next = cur.next;
            RandomListNode tmp = new RandomListNode(cur.label);
            tmp.next = cur.next;
            cur.next = tmp;
            cur = next;
        }
        cur = head;
        while(cur != null)
        {
            RandomListNode next = cur.next.next;
            RandomListNode random = cur.random;
            if(random == null)  cur.next.random = null;
            else    cur.next.random = random.next;
            cur = next;
        }
        cur = head;
        RandomListNode rst = head.next;
        while(cur != null)
        {
            RandomListNode next = cur.next.next;
            if(next == null)
                cur.next.next = null;
            else
                cur.next.next = next.next;
            cur.next = next;
            cur = next;
        }
        return rst;
    }
}
View Code

他人代码:

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) {
            return null;
        }

        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
        RandomListNode dummy = new RandomListNode(0);
        RandomListNode pre = dummy, newNode;
        while (head != null) {
            if (map.containsKey(head)) {
                newNode = map.get(head);
            } else {
                newNode = new RandomListNode(head.label);
                map.put(head, newNode);
            }
            pre.next = newNode;

            if (head.random != null) {
                if (map.containsKey(head.random)) {
                    newNode.random = map.get(head.random);
                } else {
                    newNode.random = new RandomListNode(head.random.label);
                    map.put(head.random, newNode.random);
                }
            }

            pre = newNode;
            head = head.next;
        }

        return dummy.next;
    }
}
View Code

学习之处:

  • Hashtable(node,copynode)方法也很不错嘛
  • 自己的代码太长了,应该功能进行划分,划分成多个模块,一个这么长的代码不适合维护和阅读。
原文地址:https://www.cnblogs.com/sunshisonghit/p/4339052.html