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)
代码:
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL)
return head; RandomListNode* oldNode = head;
RandomListNode* nodeLeft = NULL;
RandomListNode* newNode = NULL;
RandomListNode* newList = NULL; while (oldNode) {
nodeLeft = oldNode->next;
oldNode->next = new RandomListNode(oldNode->label);
oldNode->next->next = nodeLeft;
oldNode = nodeLeft;
} oldNode = head;
newList = head->next; while (oldNode) {
newNode = oldNode->next;
if (oldNode->random == NULL)
newNode->random = NULL;
else
newNode->random = oldNode->random->next;
oldNode = newNode->next;
} oldNode = head;
while (oldNode) {
newNode = oldNode->next;
oldNode->next = newNode->next;
oldNode = oldNode->next;
if (oldNode)
newNode->next = oldNode->next;
} return newList;
}
};