LeetCode | 138. 随机链表的复制

简介: LeetCode | 138. 随机链表的复制

LeetCode | 138. 随机链表的复制

OJ链接


思路:

  • 题目要求我们拷贝一个带next指针与random随机访问指针的链表。
  • 如果只拷贝一个只带next的指针,直接遍历目标链表依次拷贝每个节点的信息就可以了~~
  • 拷贝节点插入到原节点的后面



  • 处理copy节点的random
  • copy节点下来的尾插
struct Node* copyRandomList(struct Node* head) {
  struct Node* cur = head;
    //拷贝节点插入到原节点的后面
    while(cur)
    {
      struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        copy->val = cur->val;
        copy->next = cur->next;
        cur->next = copy;
        //cur = copy->next;
        cur = cur->next->next;
    }
    //处理copy节点的random
    cur = head;
    while(cur)
    {
        struct Node* copy = cur->next;
        if(cur->random == NULL)
        {
            copy->random = NULL;
        }
        else
        {
            copy->random = cur->random->next;
        }
        cur = cur->next->next;
    }
    //copy节点下来的尾插
    struct Node* newhead = NULL,*tail = NULL;
    cur = head;
    while(cur)
    {
        struct Node* copy = cur->next;
        struct Node* next = copy->next;
        if(tail == NULL)
        {
            newhead = tail = copy;
        }
        else
        {
            tail->next = copy;
            tail = tail->next;
        }
        copy->next = next;
        cur = next;
    }
    return newhead;
}
相关文章
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
1天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
11 4
|
2天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
8 0
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
16天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
25天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
25天前
|
索引
【力扣】142. 环形链表 II
【力扣】142. 环形链表 II
|
25天前
【力扣】19. 删除链表的倒数第 N 个结点
【力扣】19. 删除链表的倒数第 N 个结点
|
25天前
|
C语言 C++ 索引
【力扣】141. 环形链表、160. 相交链表、206.反转链表、234. 回文链表
【力扣】141. 环形链表、160. 相交链表、206.反转链表、234. 回文链表

热门文章

最新文章