剑指offer 面试题26复杂链表的复制

本文介绍了一种复杂链表的深拷贝方法,该链表中的节点除了包含指向下一个节点的next指针外,还包含指向链表中任意节点的pSibling指针。文章详细阐述了如何通过三个步骤——复制节点、连接pSibling指针和重建链表——来完成整个深拷贝过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

复制一个复杂链表。在复杂链表中,每个节点有next 指针指向下一个结点外,还有pSibling指向链表任何结点或者NULL。

 

根据作者思路实现这个需求,代码没有作者简洁。

#include <iostream>

using namespace std;

struct complexLinklist{
	char val;
	complexLinklist *next;
	complexLinklist *pSibling;
};

void copyListNode(complexLinklist *head)
{
	complexLinklist *p=head,*pre=NULL;
	char val;
	while (p!=NULL)
	{
		pre=p;
		val=p->val;
		p=p->next;
		complexLinklist *newNode=new complexLinklist;
		if (newNode==NULL)
		{
			cout<<"memory errors \n";
		}
		newNode->val=val;
		newNode->pSibling=NULL;
		pre->next=newNode;
		if (p==NULL)
		{
			newNode->next=NULL;
		}
		else{
			newNode->next=p;
		}
		
	}
}

void connectPSibling(complexLinklist *head)
{
	complexLinklist *pNode=head;
	while (pNode!=NULL)
	{
		complexLinklist *clone=pNode->next;
		if (pNode->pSibling!=NULL)
		{
			clone->pSibling=pNode->pSibling->next;
		}
		pNode=clone->next;
	}
}

complexLinklist * reconnectLinklist(complexLinklist *head)
{
	complexLinklist *pNode=head;
	complexLinklist *pCloneHead=NULL,*pCloneNode=NULL;
	/*
	算法思想来自于剑指offer,但是代码没有写的像作者简介明了。
	*/
	if (pNode!=NULL)
	{
		pCloneHead=pCloneNode=pNode->next;
	}	
	while (pNode!=NULL)
	{
			pNode->next=pCloneNode->next;
			pNode=pCloneNode->next;
			if (pNode==NULL)
			{
				pCloneNode->next=NULL;
			}
			else{
				pCloneNode->next=pNode->next;
				pCloneNode=pNode->next;
			}				
	}
	return pCloneHead;
}

complexLinklist *Clone(complexLinklist *head)
{
	copyListNode(head);
	connectPSibling(head);
	return reconnectLinklist(head);
}

void PrintLinklist(complexLinklist *head)
{
	cout<<"打印链表元素\n";
	while (head!=NULL)
	{
		cout<<head->val<<endl;
		if (head->pSibling!=NULL)
		{
			cout<<head->val<<"的psbling元素"<<head->pSibling->val<<endl;
		}
		head=head->next;
	}
}

int main()
{
	complexLinklist *head,*one,*two,*three;
	head=new complexLinklist;
	one=new complexLinklist;
	two=new complexLinklist;
	three=new complexLinklist;
	head->pSibling=one->pSibling=two->pSibling=three->pSibling=NULL;
	head->val='A';
	one->val='B';
	two->val='C';
	three->val='D';
	head->next=one;
	one->next=two;
	two->next=three;
	three->next=NULL;
	head->pSibling=two;
	three->pSibling=one;
	complexLinklist *testPoint;
	testPoint=Clone(head);
	PrintLinklist(testPoint);
	return 0;
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值