1. 原題鏈接:https://leetcode.com/problems/copy-list-with-random-pointer/
2. 解題思路
2.1 映射表
- 建立新舊節點之間的映射表:old->new,來解決復制random指標
2.2 克隆鏈表
- 創建一個包含新節點的克隆鏈表:A --> A' --> B --> B' --> C --> C' --> D --> D'
- 關鍵點:A'的random指標等于A的random指標指向的節點的next節點
3. 演算法
3.1 映射表
- 建立新舊節點之間的映射表:old->new
- 遍歷鏈表兩次:
- 第一次遍歷:構造新鏈表,只是對新鏈表的next指標進行賦值,同時建立舊節點和新建節點之間的映射表,此時不對random指標進行賦值
- 第二次遍歷:根據映射表的映射關系,對新鏈表的random指標進行賦值
3.2 克隆鏈表
- 第一步:遍歷原始鏈表:A --> B --> C --> D,創建一個包含新節點的克隆鏈表:A --> A' --> B --> B' --> C --> C' --> D --> D',注意此時不對random指標進行賦值
- 第二步:遍歷新鏈表,當遍歷到原始鏈表節點時,對該節點的下一個節點(也就是A和A'的關系)的random指標進行賦值,該random指標指向原始節點的random指標指向的下一個節點
- 第三步:遍歷新鏈表,把新節點從新鏈表中挑選出來,構成最終的copy鏈表并回傳
4. 實作
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) {
//建立新舊節點之間的映射表:old->new
map<Node*, Node*> table;
//第一次遍歷:構造新鏈表,此時不對random指標進行賦值
Node dummy(-1);
Node *cur = head;
Node *new_cur = &dummy;
for(; cur != NULL; cur = cur->next, new_cur = new_cur->next){
int v = cur->val;
Node *new_node = new Node(v);
table[cur] = new_node; //關鍵點:建立舊節點指標到新節點指標的映射
new_cur->next = new_node;
}
//第二次遍歷:對新鏈表的random指標進行賦值
cur = head;
new_cur = dummy.next;
for(; cur != NULL; cur = cur->next, new_cur = new_cur->next){
Node *r = cur->random;
Node *new_r = table[r];
new_cur->random = new_r;
}
return dummy.next;
}
};
克隆鏈表
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return head;
//copy new node and changing new node next pointer to old node next pointer and old node next pointer to new node
Node *newHead = NULL, *l1, *l2;
for(l1 = head; l1 != NULL; l1 = l1->next->next){
l2 = new Node(l1->val, l1->next, NULL);
l1->next = l2;
}
newHead = head->next;
//fixing the random pointer of the cloned list
for(l1= head; l1 != NULL; l1 = l1->next->next){
if(l1->random) l1->next->random = l1->random->next;
}
//changing the next node of both old and new list
for(l1 = head; l1 != NULL; l1 = l1->next){
l2 = l1->next;
l1->next = l2->next;
if(l2->next)l2->next = l2->next->next;
}
return newHead;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/85157.html
標籤:其他
上一篇:hdfs之客戶端讀、寫操作,元資料,Secondarynamenode,Checkpoint
下一篇:順時針列印矩陣
