Copy List with Random Pointer

来源:互联网 发布:南京大学软件学院地址 编辑:程序博客网 时间:2024/06/10 16:20

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) {        RandomListNode fake = new RandomListNode(0);        fake.next = head;        RandomListNode cur = fake;                RandomListNode copyFake = new RandomListNode(0);        RandomListNode copyCur = copyFake;        Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();                while(cur.next != null) {            RandomListNode newNode = new RandomListNode(cur.next.label);            map.put(cur.next, newNode);            copyCur.next = newNode;            copyCur = copyCur.next;            cur = cur.next;        }                cur = fake.next;        copyCur = copyFake.next;                while (cur != null) {            if (cur.random != null) {                copyCur.random = map.get(cur.random);            }            cur = cur.next;            copyCur = copyCur.next;        }        return copyFake.next;    }}

一个不用 extra space的做法:http://blog.csdn.net/linhuanmars/article/details/22463599

把每一个新的node都加在原来node的后面,最后再分割出去:

public RandomListNode copyRandomList(RandomListNode head) {    if(head == null)        return head;    RandomListNode node = head;    while(node!=null)    {        RandomListNode newNode = new RandomListNode(node.label);        newNode.next = node.next;        node.next = newNode;        node = newNode.next;    }    node = head;    while(node!=null)    {        if(node.random != null)            node.next.random = node.random.next;        node = node.next.next;    }    RandomListNode newHead = head.next;    node = head;    while(node != null)    {        RandomListNode newNode = node.next;        node.next = newNode.next;        if(newNode.next!=null)            newNode.next = newNode.next.next;        node = node.next;    }    return newHead;}

0 0
原创粉丝点击