剑指 Offer 35. 复杂链表的复制

这篇博客探讨了LeetCode中关于复杂链表复制的问题,指出错误思路会修改原始链表。博主分享了两种正确解法,一种利用辅助数据结构建立新旧节点关系,另一种是在原链表上直接操作,将新节点连接到旧节点后面,完成复制后再分离新链表,确保不破坏原结构。
摘要由CSDN通过智能技术生成

题目链接: leetcode.

错误思路,修改了原来的列表指针

[[7,null],[13,0],[11,4],[10,2],[1,0]]
Next pointer of node with label 7 from the original list was modified.

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
   
public:
    Node* copyRandomList(Node* head) {
   
        if(head == nullptr)
        	return NULL;
        Node* node1 = head;
        Node* ans = new Node(0);
        Node* node2 = ans;
        //复制所有节点,新的random指向旧的节点
        while(node1) 
        {
   
        	node2 -> next = new Node(node1 -> val);
        	node2 = node2 -> next;
        	if(node1 -> random)
        		node2 -> random = node1 -> random;
        	node1 = node1 -> next;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值