输入复杂链表如图,复制该链表。

每天一道算法题目(20)——复杂链表的拷贝



思路:

       如图。传统的做法是先复制next指针部分,然后对于每个节点的random部分,则需要遍历整个链表查找对应节点。时间复杂度为O(n.^2)。时间这里总结一种时间复杂度为O(n)空间复杂度为O(1)的方法。

       第一步。简单复制next指针部分,并将拷贝节点和源节点链接一起。结果如下图:

       第二步。遍历链表,遇到random指针非空的,则其对应拷贝节点,也就是他的下一节点的random应该指向当前节点random指向的下一节点。例如A指向C,则A*必然指向C*,以此类推。

       第三步。拆分节点,偶数节点串接为拷贝链表,奇数节点串接为原链表。


每天一道算法题目(20)——复杂链表的拷贝


代码:

typedef struct Tree{
	Tree* next;
	Tree* random;
}* node;

node copy(node head){
	if(!head)
		return NULL;

	//复制链表
	node temp=head;
	node copyNode=NULL;
	while(temp){
		copyNode=new Tree();
		copyNode->next=temp->next;
		temp->next=copyNode;
		temp=copyNode->next;
	}

	//复制随机指针
	temp=head;
	while(temp){
		if(!temp->random)
			temp->next->random=temp->random->next;
		temp=temp->next->next;
	}

	//将偶数链表拆分出来连接到一起即为链表的拷贝,当然应该将奇数部分重新整理还原
	temp=head;
	node copyHead=NULL;
	copyNode=copyHead=temp->next;
	temp->next=copyNode->next;
	temp=temp->next;
	while(temp){
		copyNode->next=temp->next;
		copyNode=copyNode->next;
		temp->next=copyNode->next;
		temp=temp->next;
	}
	return copyHead;
}




相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
  • 2021-10-03
  • 2021-06-14
  • 2022-12-23
  • 2022-01-05
猜你喜欢
  • 2021-05-27
  • 2022-12-23
  • 2022-03-09
  • 2021-09-20
  • 2022-12-23
  • 2021-09-11
  • 2022-02-27
相关资源
相似解决方案