138. Copy List with Random Pointer

来源:互联网 发布:订餐的软件 编辑:程序博客网 时间:2024/06/07 05:56

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.

/** * Definition for singly-linked list with a random pointer. * class RandomListNode { *     int label; *     RandomListNode next, random; *     RandomListNode(int x) { this.label = x; } * }; */public class Solution {    public RandomListNode copyRandomList(RandomListNode head) {        if (head  == null) return head;        RandomListNode node = head;        while (node != null) {            RandomListNode tmp = node.next;            RandomListNode add = new RandomListNode(node.label);            add.next = node.next;            node.next = add;            node = tmp;        }        node = head;        while (node != null) {            if (node.random != null) node.next.random = node.random.next;            node = node.next.next;        }        RandomListNode dummy = new RandomListNode(0);        RandomListNode cursor = dummy;        node = head;        while (node != null) {            RandomListNode tmp = node.next.next;            cursor.next = node.next;            cursor = cursor.next;            node.next = tmp;            node = tmp;        }        return dummy.next;    }}
/** * Definition for singly-linked list with a random pointer. * class RandomListNode { *     int label; *     RandomListNode next, random; *     RandomListNode(int x) { this.label = x; } * }; */public class Solution {    public RandomListNode copyRandomList(RandomListNode head) {        if (head  == null) return head;        HashMap<RandomListNode, RandomListNode> map = new HashMap<>();        RandomListNode node = head;        while (node != null) {            map.put(node, new RandomListNode(node.label));            node = node.next;        }        node = head;        while (node != null) {            RandomListNode tmp = map.get(node);            tmp.next = map.get(node.next);            tmp.random = map.get(node.random);            node = node.next;        }        return map.get(head);    }}
0 0
原创粉丝点击