什么是复杂链表
复杂链表就是,有一个单链表有两个指针,一个指针指向下一个节点,另一个指针指向任何节点,可以是指向空,可以指向自己,可以指向链表中的任意节点。
形如:
复杂链表的结构
有两个指针,一个next,一个random,还有一个数据。
struct Node
{
int _data;//值
Node* _next;//指向下一个节点的指针
Node* _random;//指向任意节点的指针
};
复杂链表的复制简单实现
有这样一个复杂链表:
分三个部分进行复制:
第一步:
把每个节点复制一个链在原来的那个节点上,新节点的random置空。
第二步:将新节点的random链接起来
第三步:将两个链表摘开,就是将新复制的节点摘下来,链接起来
代码:
Node* ComplexCopy(Node* head)
{
Node* cur = head;
//复制新节点连在原来的后面,将新节点的random置空
while (cur)
{
Node* tmp = new Node;
tmp->_data = cur->_data;
tmp->_next = cur->_next;
tmp->_random = NULL;
cur->_next = tmp;
cur = tmp->_next;
}
//将新节点的random链接起来
cur = head;
Node* tmp = NULL;
while (cur)
{
tmp = cur->_next;
if (cur->_random)
tmp->_random = cur->_random->_next;
cur = tmp->_next;
}
//摘节点
cur = head;
Node* newHead = head->_next;
Node* next = NULL;
while (cur)
{
next = cur->_next;
cur->_next = next->_next;
tmp = cur->_next;
if (tmp)
{
next->_next = tmp->_next;
next = tmp->_next;
}
cur = tmp;
}
return newHead;
}
整体代码:
#include <iostream>
using namespace std;
struct Node
{
int _data;//值
Node* _next;//指向下一个节点的指针
Node* _random;//指向任意节点的指针
};
Node* ComplexCopy(Node* head)
{
Node* cur = head;
//复制新节点连在原来的后面,将新节点的random置空
while (cur)
{
Node* tmp = new Node;
tmp->_data = cur->_data;
tmp->_next = cur->_next;
tmp->_random = NULL;
cur->_next = tmp;
cur = tmp->_next;
}
//将新节点的random链接起来
cur = head;
Node* tmp = NULL;
while (cur)
{
tmp = cur->_next;
if (cur->_random)
tmp->_random = cur->_random->_next;
cur = tmp->_next;
}
//摘节点
cur = head;
Node* newHead = head->_next;
Node* next = NULL;
while (cur)
{
next = cur->_next;
cur->_next = next->_next;
tmp = cur->_next;
if (tmp)
{
next->_next = tmp->_next;
next = tmp->_next;
}
cur = tmp;
}
return newHead;
}
void TestComplexCopy()//测试
{
Node* ptr1 = new Node;
Node* ptr2 = new Node;
Node* ptr3 = new Node;
Node* ptr4 = new Node;
ptr1->_data = 3;
ptr1->_next = ptr2;
ptr1->_random = ptr3;
ptr2->_data = 9;
ptr2->_next = ptr3;
ptr2->_random = NULL;
ptr3->_data = 1;
ptr3->_next = ptr4;
ptr3->_random = ptr3;
ptr4->_data = 5;
ptr4->_next = NULL;
ptr4->_random = ptr2;
ComplexCopy(ptr1);
}
int main()
{
TestComplexCopy();
return 0;
}