什么是复杂链表?

复杂链表的节点包括三个成员变量:一个T类型的变量,一个指向下个节点的指针,一个随机指向的指针。

复杂链表的复制需要注意:复制之后的链表的每个节点的随机指针的指向需要和复制之前的链表的节点的随机指针指向的节点一样。

节点:

struct ComplexNode
{
	ComplexNode(int data)
		:_data(data)
		,_next(NULL)
		,_random(NULL)
	{}
	int _data;
	ComplexNode* _next;
	ComplexNode* _random;
};

实例:

wKioL1cVke_D2BJKAAAwM1Wo2wk295.png

复制链表的步骤:

1、复制每个节点,将其插在原节点的后面,这样,复制节点的随机指针指向的节点是原节点的随机指针指向的节点之后的节点。

wKiom1cVk-mwMTtbAAAz5ShB-K4051.png2、random指向

3、拆分链表

代码实现:

ComplexNode* CopyComplexList(ComplexNode* list)
{
	    ComplexNode* cur=list;
		while(cur)//复制节点并插到原节点的后面
		{
			ComplexNode* newnode = new ComplexNode(cur->_data);
			newnode->_next=cur->_next;
			cur->_next=newnode;
			cur=newnode->_next;
		}
		cur=list;//cur指向头结点
		while(cur)//置random
		{
			if(cur->_random!=NULL)
			{
				cur->_next->_random=cur->_random->_next;
			}
			cur=cur->_next->_next;
		}
		cur=list;
		ComplexNode* tmp1=NULL;//拆分链表,tmp2为复制之后的链表
		ComplexNode* tmp2=NULL;
		if(cur!=NULL)
		{
			tmp1=tmp2=cur->_next;
			cur->_next=tmp1->_next;
			cur=cur->_next;			
		}
		while(cur!=NULL)
		{
			tmp1->_next=cur->_next;
			tmp1=tmp1->_next;
			cur->_next=cur->_next->_next;
			cur=cur->_next;
		}
		return tmp2;
}