leetcode [138] 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.
Example 1:
Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}
Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.
Note:
- You must return the copy of the given head as a reference to the cloned list.
题目大意:
深复制一个链表,该链表每一个节点有两个指针,一个指向下一个节点,一个指向链表中的任意一个节点。
解法:
1.先对链表上每一个节点进行复制,并插入该节点之后。
2.在从头遍历链表,这时奇数节点是原链表的节点,偶数节点是新链表的节点。
有p.next.random=p.random.next的关系。
3.将新链表和旧链表进行分离。
java:
class Solution { public Node copyRandomList(Node head) { if(head==null) return null; Node p=head; while(p!=null){ Node newNode=new Node(p.val,p.next,null); p.next=newNode; p=p.next.next; } p=head; while(p!=null){ if(p.random!=null) p.next.random=p.random.next; p=p.next.next; } p=head; Node newhead=p.next; while(p!=null&&p.next!=null){ Node next=p.next; p.next=next.next; p=next; } return newhead; } }