Copy List With Random Pointer

来源:互联网 发布:淘宝商业摄影需要器材 编辑:程序博客网 时间:2024/05/23 13:22

使用HashTable

/** * 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 null;        }        RandomListNode dummy1 = new RandomListNode(-1);        RandomListNode dummy2 = new RandomListNode(-1);        dummy1.next = head;        RandomListNode ptr1 = dummy1, ptr2 = dummy2;                Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();                while (ptr1.next != null) {            ptr1 = ptr1.next;            ptr2.next = new RandomListNode(ptr1.label);            ptr2 = ptr2.next;            map.put(ptr1, ptr2);        }        ptr2.next = null;                ptr1 = dummy1;        ptr2 = dummy2;        while (ptr1.next != null) {            ptr1 = ptr1.next;            map.get(ptr1).random = map.get(ptr1.random);        }        return dummy2.next;    }}

不使用HashTable

/** * 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 null;        }                RandomListNode ptr = head;        while (ptr != null) {            RandomListNode copy = new RandomListNode(ptr.label);            copy.next = ptr.next;            ptr.next = copy;            ptr = copy.next;        }                ptr = head;        while (ptr != null) {            if (ptr.random != null) {                ptr.next.random = ptr.random.next;            }            ptr = ptr.next.next;        }                ptr = head;        RandomListNode newHead = head.next;        while (ptr != null) {            RandomListNode temp = ptr.next;            ptr.next = temp.next;            if (temp.next != null) {                temp.next = temp.next.next;            }            ptr = ptr.next;        }        return newHead;    }}




0 0