LeetCode 138. Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

题目的意思很明确——复杂链表的复制问题,链表的指针域不仅包括指向下一个节点的next,还包括指向其他任意节点的指针random,这道题乍一看非常复杂,如果逐个节点赋值复杂度非常高,但是有一个比较巧妙的思路步骤如下:

  • 先判断头指针是否为空,若为空,返回空指针
  • 再进行节点的复制,将每一个节点的复制节点连接在原来节点之后
  • 然后再从头遍历链表,进行random指针的复制
  • 最后将复制完成的链表从原来链表中断开,返回新的头指针

代码如下:

 1 /**
 2  * Definition for singly-linked list with a random pointer.
 3  * struct RandomListNode {
 4  *     int label;
 5  *     RandomListNode *next, *random;
 6  *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     RandomListNode *copyRandomList(RandomListNode *head) {
12         if (!head)
13            return nullptr;
14         RandomListNode *newHead, *l1, *l2;
15         for (l1 = head; l1 != nullptr; l1 = l1->next->next)
16         {
17             l2 = new RandomListNode(l1->label);
18             l2->next = l1->next;
19             l1->next = l2;
20         }
21         newHead = head->next;
22         //调整赋值之后新节点random指针
23         for (l1 = head; l1 != nullptr; l1 = l1->next->next)
24             if(l1->random != nullptr)
25                 l1->next->random = l1->random->next;
26         //断开已经连接好的链表
27         for (l1 = head; l1 != nullptr; l1 = l1->next)
28         {
29             l2 = l1->next;
30             l1->next = l2->next;
31             if (l2->next != nullptr)
32             l2->next = l2->next->next;
33         }
34         return newHead;
35     }
36 };

时间复杂度:O(N)

空间复杂度:O(1)

参考资料:https://leetcode.com/problems/copy-list-with-random-pointer/discuss/43497/ 

一刷:31行忘记判断是否为空,for循环中变量前两次变化为next->next,容易出错

原文地址:https://www.cnblogs.com/dapeng-bupt/p/8261744.html