【Leetcode】Copy List with Random Pointer

来源:互联网 发布:windows ble蓝牙开发 编辑:程序博客网 时间:2024/04/28 14:48

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.

一个比较理想的方式是,我们先处理这个 1 ->2 ->3 ->4,把它变成1 ->1' ->2 ->2' ->3 ->3' ->4 ->4'

然后我们再重新赋值random,因为既然已经建立了这个结构,所有赋值都可以在while()中找到

最后我们break这个结构,只保留所有的(n'),也非常简单,只要把tmp.next = tmp.next.next 就好了。

我分module,而且给出了prinf函数,用于打印出你之前想放进去的node

package testAndfun;import java.util.HashMap;import testAndfun.RandomListNode;public class copyListRandomPo {//HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();public static void main(String[] args){copyListRandomPo cr =new copyListRandomPo();RandomListNode n1 = new RandomListNode(1);RandomListNode n2 = new RandomListNode(2);RandomListNode n3 = new RandomListNode(3);n1.next = n2;n2.next = n3;n1.random = n2;n3.random = n1;prinf(n1);RandomListNode new1 = cr.copyRandomList(n1);prinf(new1);}private static void prinf(RandomListNode n){while(n!=null){if(n.random!=null)System.out.print(n.label+"("+n.random.label+")"+"->");elseSystem.out.print(n.label+"->");n = n.next;}System.out.println();}private void copyNext(RandomListNode head) {        while (head != null) {            RandomListNode newNode = new RandomListNode(head.label);            newNode.random = head.random;            newNode.next = head.next;            head.next = newNode;            head = head.next.next;        }    }    private void copyRandom(RandomListNode head) {        while (head != null) {            if (head.next.random != null) {                head.next.random = head.random.next;            }            head = head.next.next;        }    }    private RandomListNode splitList(RandomListNode head) {        RandomListNode newHead = head.next;        while (head != null) {            RandomListNode temp = head.next;            head.next = temp.next;            head = head.next;            if (temp.next != null) {                temp.next = temp.next.next;            }        }        return newHead;    }    public RandomListNode copyRandomList(RandomListNode head) {if (head == null) {            return null;        }        copyNext(head);        copyRandom(head);        return splitList(head);    }}


0 0
原创粉丝点击