LeetCode Copy List with Random Pointer

本文介绍了一种不使用额外空间复制带有随机指针的复杂单链表的方法。通过三个步骤实现:1) 在每个节点后插入其副本;2) 设置副本的随机指针;3) 分离原链表和副本链表。

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

题目:

 A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list. 

题意:

将一个复杂单链表进行复制,注意:是复制,不是直接返回。

题解:

此题在《剑指offer》中出现了,面试题26,而且提供了3种方法来解决。其中我这里是采用了第三种方法。这种方法是不采用辅助空间来解决的,分三步来做。

第一步:根据原始链表的每个节点N创建对应的N’。然后我们把N’链接在N的后面。如下图所示:

 

    A ----> A' ----> B ----> B' ----> C ----> C' ----> D ----> D'.....

第二步:设置复制出来的节点的m_pSibiling,也就是指向不同的链。假设原始链表上的N的m_pSibiling指向节点S,那么对应复制出来的N’的next就指向S的next。


第三步:将这个单链表分拆成两个表,把奇数位置的节点用next连接起来的就是原始的链表,偶数位置连接起来的就是新复制出来的链表。

代码如下:

public RandomListNode copyRandomList(RandomListNode head)
	{
		if(head == null)//这道题目,有点特别,如果碰到head.next == null的情况,也不能直接返回head,否则就会认为是直接返回的,所以哪怕只有一个节点,也必须要复制才能做
			return head;
		RandomListNode node = CloneNode(head);
		ConnectSiblingNodes(node);
		return ReconnectNodes(node);
	}
	public RandomListNode CloneNode(RandomListNode root)
	{
		RandomListNode node = root;    
		while(node != null)
		{
			RandomListNode pCloned = new RandomListNode(Integer.MIN_VALUE);    //首先这里要当心,因为不能复制,所以采用-1
			pCloned.label = node.label;
			pCloned.next = node.next;
			pCloned.random = null;
			node.next = pCloned;
			node = pCloned.next;
		}
		return root;
	}
	public void ConnectSiblingNodes(RandomListNode root)
	{
		RandomListNode node = root;
		while(node != null)
		{
			RandomListNode pCloned = node.next;
			if(node.random != null)
			{
				pCloned.random = node.random.next;
			}
			node = pCloned.next;
		}
	}
	public RandomListNode ReconnectNodes(RandomListNode root)
	{
		RandomListNode node = root;
		RandomListNode pClonedHead = null;
		RandomListNode pClonedNode = null;
		if(node != null)
		{
			pClonedHead = pClonedNode = node.next;
			node.next = pClonedNode.next;
			node = node.next;
		}
		while(node != null)
		{
			pClonedNode.next = node.next;
			pClonedNode = pClonedNode.next;
			node.next = pClonedNode.next;
			node = node.next;
		}
		return pClonedHead;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值