[leetcode] Copy List with Random Pointer
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.
https://oj.leetcode.com/problems/copy-list-with-random-pointer/
思路:在每个原来的节点后面插入新节点;复制random指针;分解至两个独立列表
public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if (head == null) return null; // copy the next RandomListNode cur = head; while (cur != null) { RandomListNode tmp = new RandomListNode(cur.label); tmp.next = cur.next; cur.next = tmp; cur = tmp.next; } // copy the random pointer cur = head; while (cur != null) { RandomListNode tmp = cur.next; if (cur.random != null) tmp.random = cur.random.next; cur = tmp.next; } // decomposite RandomListNode res = head.next; cur=head; while (cur != null) { RandomListNode tmp = cur.next; cur.next = tmp.next; if (tmp.next != null) tmp.next = tmp.next.next; cur = cur.next; } return res; } }
第二遍记录:
第三遍记录:
注意复制random的时候,先判断random是否为空
注意各个指针的变换,可以建立一些临时节点指针方便操作,比如post。
public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if(head==null) return null; RandomListNode cur = head; while(cur!=null){ RandomListNode newNode = new RandomListNode(cur.label); newNode.next=cur.next; cur.next=newNode; cur=newNode.next; } cur = head; while(cur!=null){ if(cur.random!=null) cur.next.random = cur.random.next; cur=cur.next.next; } cur = head; RandomListNode res = head.next; while(cur!=null){ RandomListNode post =cur.next; cur.next=post.next; if(cur.next!=null) post.next = post.next.next; cur =cur.next; } return res; } }
参考:
http://fisherlei.blogspot.com/2013/11/leetcode-copy-list-with-random-pointer.html