您的位置:首页 > 编程语言 > Java开发

[Leetcode] Copy List with Random Pointer (Java)

2014-02-15 15:51 351 查看
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.

带随机指针的单链表复制

先整理成 head->copyhead->seconde->copysecond->……->last->copylast的形式

然后遍历链表处理random指针

最后进行拆分

public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null)
return null;
RandomListNode cur = head;
while(cur!=null){
RandomListNode tmp = new RandomListNode(cur.label);
tmp.next=cur.next;
cur.next=tmp;
cur=tmp.next;
}
cur = head;
while(cur!=null){
RandomListNode copy = cur.next;
if(cur.random!=null)
copy.random = cur.random.next;
cur=copy.next;
}
RandomListNode ret = new RandomListNode(-1);
RandomListNode pre = ret;
cur = head;
while(cur!=null){
pre.next = cur.next;
cur.next = cur.next.next;
pre=pre.next;
cur=cur.next;
}
return ret.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: