您的位置:首页 > 运维架构

【Leetcode】Copy List with Random Pointer

2016-01-29 04:26 399 查看
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+")"+"->");
else
System.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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: