题目描述:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:
插入结点;random指针赋值;拆分链表。
代码:
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if (head == NULL) return head;
Node* pre = head;
while(pre != NULL) {
Node* copy = new Node(pre->val);
copy->next = pre->next;
pre->next = copy;
pre = copy->next;
}
pre = head;
while(pre != NULL) {
if (pre->random != NULL)
pre->next->random = pre->random->next;
pre = pre->next->next;
}
Node* head1 = head;
Node* head2 = head->next;
Node* phead = head2;
while(head2->next != NULL) {
head1->next = head2->next;
head1 = head1->next;
head2->next = head1->next;
head2 = head2->next;
}
head1->next = NULL;
return phead;
}
};