LeetCode 剑指 Offer 35. 复杂链表的复制 题解 两种解法 C/C++

主要思路

方法一:map映射
首先建立对应结点 ,key值为旧的结点,value为相对应的新结点;
建立next和random连接即可

方法二:先拼接在拆分
先进行连接,连成1 1’ 2 2’ 3 3’…的形式 1’为1的复制
然后连接random
最后拆分 详见代码


class Node {
public:
	int val;
	Node* next;
	Node *random;

	Node(int _val) {
		val = _val;
		next = nullptr;
		random = nullptr;
	}
};

//方法一  map映射
class Solution {
public:
	Node* copyRandomList(Node* head) {
		if(head==nullptr)return nullptr;
		map<Node*,Node*> nnMap;
		Node* cur= head;
		while(cur) {//建立对应的新结点
			nnMap[cur] = new Node(cur->val);
			cur = cur->next;
		}
		cur = head;
		while(cur!=nullptr) {
			nnMap[cur]->next = nnMap[cur->next];
			nnMap[cur]->random = nnMap[cur->random];
			cur= cur->next;
		}

		return nnMap[head];

	}
};


//方法二 拼接拆分
class Solution {
public:
	Node* copyRandomList(Node* head) {
		if(head==nullptr)return nullptr;
		Node *p = head;
		while(p!=nullptr) {//先进行连接,连成1 1' 2 2' 3 3'...的形式 1'为1的复制  
			Node *tmp = new Node(p->val);
			tmp->next = p->next;
			p->next = tmp;
			p = tmp->next;
		}
		p = head;

		while(p!=nullptr) {//再连接random
			if(p->random) {
				p->next->random = p->random->next;
			}
			p = p->next->next;
		}
		//最后拆分
		p = head->next;
		Node *cur = head;
		Node *ret = head->next;
		while(p->next!=nullptr) {//新链表就两个结点的话就直接拆了 不进入循环
			cur->next = cur->next->next;//原链表
			p->next = p->next->next;//拆分出的新链表
			cur = cur->next;
			p = p->next;
		}
		cur->next =nullptr;
		return ret;


	}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值