Copy List with Random Pointer -- LeetCode

本思路是这样的,对链表进行三次扫描,第一次扫描对每个结点进行复制,然后把复制出来的新节点接在原结点的next,也就是让链表变成一个重复链表,就是新旧更替;第二次扫描中我们把旧结点的随机指针赋给新节点的随机指针,因为新结点都跟在旧结点的下一个,所以赋值比较简单,就是node.next.random = node.random.next,其中node.next就是新结点,因为第一次扫描我们就是把新结点接在旧结点后面。现在我们把结点的随机指针都接好了,最后一次扫描我们把链表拆成两个,第一个还原原链表,而第二个就是我们要求的复制链表。因为现在链表是旧新更替,只要把每隔两个结点分别相连,对链表进行分割即可。这个方法总共进行三次线性扫描,所以时间复杂度是O(n)。而这里并不需要额外空间,所以空间复杂度是O(1)。比起上面的方法,这里多做一次线性扫描,但是不需要额外空间,还是比较值的。实现的代码如下:

#include<iostream>
using namespace std;
#define STOP system("pause")

struct RandomListNode {
	int label;
	RandomListNode *next, *random;
	RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};

class Solution {
public:
	RandomListNode *copyRandomList(RandomListNode *head) {
		if (!head) return NULL;
		//1.intsert node
		RandomListNode* p_cur_node = head;
		while (p_cur_node){
			RandomListNode* tmp = new RandomListNode(p_cur_node->label);
			tmp->next = p_cur_node->next;
			p_cur_node->next = tmp;
			p_cur_node = tmp->next;
		}
		//2.insert random node
		p_cur_node = head;
		while (p_cur_node){
			if (p_cur_node->random) p_cur_node->next->random = p_cur_node->random->next;
			else p_cur_node->next->random = nullptr;
			p_cur_node = p_cur_node->next->next;
		}
		//split thest two list
		RandomListNode* p_new_head = new RandomListNode(-1);
		RandomListNode* p_new_cur = p_new_head;
		p_cur_node = head;
		while (p_cur_node){
			p_new_cur->next = p_cur_node->next;
			p_new_cur= p_new_cur->next;
			p_cur_node->next = p_cur_node->next->next;
			p_cur_node = p_cur_node->next;
		}
		return p_new_head->next;
	}
};
int main(){
	RandomListNode* head = nullptr;
	Solution ss;
	ss.copyRandomList(head);
	STOP;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值