- 时间限制:1秒空间限制:32768K
- 通过比例:19.61%
- 最佳记录:0 ms|8552K
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点)。
思路:
乍一看,还以为只是简单的链表复制,后来发现,还有一个任意指针,复制这个指针才是问题难度的核心。因此,将该题链表复制分解为普通指针复制与任意指针复制两部分,这两部分又都符合普通指针复制的思路。
指针结构:
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
首先复制普通指针。
RandomListNode *head = pHead;
while (head != NULL) {
RandomListNode *cur = new RandomListNode(head->label);
cur->next = head->next;
head->next = cur;
head = cur->next;
cur->random = NULL;
}
再复制random指针。
head = pHead;
RandomListNode *cur = head->next;
while (head != nullptr) {
if (head->random != NULL)
cur->random = head->random->next;
head = cur->next;
cur = head->next;
}
将原来链表与复制完的链表分离
head = pHead;
RandomListNode *new_head = pHead->next;
cur = head->next;
head->next = cur->next;
head = head->next;
while (head != NULL) {
cur->next = head->next;
cur = cur->next;
head->next = cur->next;
head = head->next;
}
复制完毕。
完整代码如下:
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 == NULL) return NULL;
RandomListNode *head = pHead;
while (head != NULL) {
RandomListNode *cur = new RandomListNode(head->label);
cur->next = head->next;
head->next = cur;
head = cur->next;
cur->random = NULL;
}
head = pHead;
RandomListNode *cur = head->next;
while (head != nullptr) {
if (head->random != NULL)
cur->random = head->random->next;
head = cur->next;
cur = head->next;
}
head = pHead;
RandomListNode *new_head = pHead->next;
cur = head->next;
head->next = cur->next;
head = head->next;
while (head != NULL) {
cur->next = head->next;
cur = cur->next;
head->next = cur->next;
head = head->next;
}
return new_head;
}
};