剑指 Offer 35. 复杂链表的复制
思路
方法一:哈希表
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 Node* next; 7 Node* random; 8 9 Node(int _val) { 10 val = _val; 11 next = NULL; 12 random = NULL; 13 } 14 }; 15 */ 16 class Solution { 17 public: 18 Node* copyRandomList(Node* head) { 19 unordered_map<Node *, Node *> mp; 20 Node *p = head; 21 while(p != NULL) { 22 mp[p] = new Node(p->val); 23 p = p->next; 24 } 25 26 p = head; 27 while(p != NULL) { 28 mp[p]->next = mp[p->next]; 29 mp[p]->random = mp[p->random]; 30 p = p->next; 31 } 32 33 return mp[head]; 34 35 } 36 };
复杂度分析
时间复杂度:O(n)。
空间复杂度:O(n)。长度为n的链表,需要构造一个大小为n的<Node*, Node*>的哈希表,所以空间复杂度为O(n)。
方法二:迭代新旧节点交错的链表
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 Node* next; 7 Node* random; 8 9 Node(int _val) { 10 val = _val; 11 next = NULL; 12 random = NULL; 13 } 14 }; 15 */ 16 class Solution { 17 public: 18 /* 19 Old List: A --> B --> C --> D 20 InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' 21 */ 22 Node* copyRandomList(Node* head) { 23 if(head == NULL) 24 return NULL; 25 //将1->2->3 拼为 1 -> 1`-> 2 -> 2`-> 3 -> 3` 26 Node *p = head; 27 while(p != NULL) { 28 Node *newNode = new Node(p->val); 29 newNode->next = p->next; 30 p->next = newNode; 31 p = newNode->next; 32 } 33 34 //连接random指针 35 p = head; 36 while(p != NULL) { 37 if(p->random) 38 p->next->random = p->random->next; 39 else 40 p->next->random = NULL; 41 p = p->next->next; 42 } 43 44 //分离两个链表 45 p = head; 46 Node *newHead = head->next; 47 Node *q; 48 while(p != NULL) { 49 q = p->next; 50 p->next = q->next; 51 p = q->next; 52 if(p) 53 q->next = p->next; 54 else 55 q->next = NULL; 56 } 57 58 return newHead; 59 } 60 };
复杂度分析
时间复杂度:O(n)
空间复杂度:O(1)