【leetCode138】复制带随机指针的链表

简介: 【leetCode138】复制带随机指针的链表

只有一条路不能选择—那就是放弃的路;只有一条路不能拒绝—那就是成长的路。

c59d82ca1845cf826f173035f616c06d_3b537831091342289558b6a8742f83ac.jpeg

今天我来讲一下力扣138题. 复制带随机指针的链表

138. 复制带随机指针的链表 - 力扣(Leetcode)

目录

题目:

第一步:

代码展示:

第二步:

代码展示:

第三步:

代码展示:

运行测试:


题目:

这道题解法分为三个步骤:

  1. 在原结点的基础上再拷贝一份结点,每一个结点和原来的结点一样连接到一起
  2. 设置拷贝结点的random值
  3. 拷贝结点解下去,并链接组成新的链表,最后将原结点恢复

第一步:

代码展示:

struct Node* cur=head;
    while(cur)
    {
        struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        struct Node* next = cur->next;
        copy->val = cur->val;
        //插入
        cur->next = copy;
        copy->next = next;
        cur = next;
    }

第二步:

代码展示:

 cur = head;
    while(cur)
    {
        struct Node* copy = cur->next;
        //struct Node* next = copy->next;
        if(cur->random == NULL)
        {
            copy->random = NULL;
        }
        else
        {
            copy->random = cur->random->next;
        }
        cur=cur->next->next;
    }

第三步:

代码展示:

 cur= head;
    struct Node* newhead = NULL , *newtail =NULL;
    while(cur)
    {
        struct Node* copy = cur->next;
        struct Node* next = copy->next;
        cur->next = next;
        if(newtail == NULL)
        {
            newhead = newtail = copy;
        }
        else
        {
            newtail->next = copy;
            newtail = newtail->next;
        }
        cur = next;
    }
    return newhead;
}

运行测试:


相关文章
|
1天前
|
索引
LeetCode438题(无敌双指针——滑动窗口)
LeetCode438题(无敌双指针——滑动窗口)
|
1天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
13 4
|
1天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
10 0
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
1天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
1天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
1天前
|
索引
【力扣】142. 环形链表 II
【力扣】142. 环形链表 II
|
1天前
【力扣】19. 删除链表的倒数第 N 个结点
【力扣】19. 删除链表的倒数第 N 个结点
|
1天前
|
C语言 C++ 索引
【力扣】141. 环形链表、160. 相交链表、206.反转链表、234. 回文链表
【力扣】141. 环形链表、160. 相交链表、206.反转链表、234. 回文链表