剑指offer——35. 复杂链表的复制

35. 复杂链表的复制

NowCoder

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。

1
2
3
4
5
6
7
8
9
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

解题思路

第一步,在每个节点的后面插入复制的节点。


第二步,对复制节点的 random 链接进行赋值。


第三步,拆分。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(!pHead) return NULL;
RandomListNode *cur = pHead;
while(cur){
RandomListNode *node = new RandomListNode(cur->label);
node->next = cur->next;
cur->next = node;
cur = node->next;
}//直到cur指向了原先链表的结尾null处
cur = pHead;
RandomListNode *p;
while(cur){
p = cur->next;
if(cur->random){
p->random = cur->random->next;

}
cur = p->next;
}

RandomListNode *pCloneHead = pHead->next;
RandomListNode *tmp;
cur = pHead;
while(cur->next){
tmp = cur->next;
cur->next =tmp->next;
cur = tmp;
}
return pCloneHead;
}
};
创作不易,欢迎打赏!
-------------本文结束感谢您的阅读-------------