1,问题描述
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 * Definition for singly-linked list with a random pointer. 3 * class RandomListNode { 4 * int label; 5 * RandomListNode next, random; 6 * RandomListNode(int x) { this.label = x; } 7 * }; 8 */
2,边界条件:root==null情况可以处理,所以没有边界条件,不需要特殊处理
3,解题思路:先不管random指针,把链表节点依次复制,不过不是生成一个新的链表,而是把新节点放在原节点的next。然后再根据random指针把新节点的random指针指向原节点的next,即新节点。最后把大链表分离,恢复旧链表,把新节点生成一个新链表,即为旧链表的deep copy。
4,代码实现
1 public RandomListNode copyRandomList(RandomListNode head) { 2 if (head == null) { 3 return null; 4 } 5 RandomListNode cur = head; 6 while (cur != null) { 7 RandomListNode node = new RandomListNode(cur.label); 8 node.next = cur.next; 9 cur.next = node; 10 cur = node.next; 11 } 12 13 cur = head; 14 while (cur != null && cur.next != null) { 15 if (cur.random != null) { 16 cur.next.random = cur.random.next; 17 } 18 cur = cur.next.next; 19 } 20 21 RandomListNode dummy = new RandomListNode(-1); 22 // RandomListNode copyCur = head.next;//这种写法在leetcode不通过,在lintcode上面能通过 23 // dummy.next = copyCur; 24 // cur = head.next.next; 25 RandomListNode copyCur = dummy;//这里是注意下,比上面写法简洁,可以处理head=null的情况 26 cur = head; 27 while (cur != null && cur.next != null) { 28 copyCur.next = cur.next; 29 cur.next = cur.next.next; 30 cur = cur.next; 31 copyCur = copyCur.next; 32 } 33 return dummy.next; 34 }
5,时间复杂度:O(n),空间复杂度:O(1)
6,api:无