【Leetcode】【Hard】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.
解题思路:
本题要求新建一个链表,使其完全等于输入链表,相当于对输入链表深复制。
题目的难点在于,原链表中有random指针,指向原链表对应的结点。当新链表建立时,需要对新结点的random指针赋值,使其指向新链表中的对应结点。这样就不能简单的复制地址,需要在新结点建立后,再找到对应正确的地址。暴力解法的时间复杂度为o(n2)。
o(n)的解法:
将每一个新结点,建立在旧结点的后面,形成:old1->new1->old2->new2->...oldN->newN->...;o(n)
建立后,重新遍历这个加长链表,new1->random = old1->random->next;o(n)
最后将新旧链表拆分;o(n)
最终时间复杂度为o(n),空间复杂度为o(1)
代码:
1 /** 2 * Definition for singly-linked list with a random pointer. 3 * struct RandomListNode { 4 * int label; 5 * RandomListNode *next, *random; 6 * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 RandomListNode *copyRandomList(RandomListNode *head) { 12 if (head == NULL) 13 return head; 14 15 RandomListNode* oldNode = head; 16 RandomListNode* nodeLeft = NULL; 17 RandomListNode* newNode = NULL; 18 RandomListNode* newList = NULL; 19 20 while (oldNode) { 21 nodeLeft = oldNode->next; 22 oldNode->next = new RandomListNode(oldNode->label); 23 oldNode->next->next = nodeLeft; 24 oldNode = nodeLeft; 25 } 26 27 oldNode = head; 28 newList = head->next; 29 30 while (oldNode) { 31 newNode = oldNode->next; 32 if (oldNode->random == NULL) 33 newNode->random = NULL; 34 else 35 newNode->random = oldNode->random->next; 36 oldNode = newNode->next; 37 } 38 39 oldNode = head; 40 while (oldNode) { 41 newNode = oldNode->next; 42 oldNode->next = newNode->next; 43 oldNode = oldNode->next; 44 if (oldNode) 45 newNode->next = oldNode->next; 46 } 47 48 return newList; 49 } 50 };