C語言數(shù)據(jù)結構之復雜鏈表的拷貝
題目:
給你一個長度為 n 的鏈表,每個節(jié)點包含一個額外增加的隨機指針 random ,該指針可以指向鏈表中的任何節(jié)點或空節(jié)點。
構造這個鏈表的 深拷貝。 深拷貝應該正好由 n 個 全新 節(jié)點組成,其中每個新節(jié)點的值都設為其對應的原節(jié)點的值。新節(jié)點的 next 指針和 random 指針也都應指向復制鏈表中的新節(jié)點,并使原鏈表和復制鏈表中的這些指針能夠表示相同的鏈表狀態(tài)。復制鏈表中的指針都不應指向原鏈表中的節(jié)點 。
例如,如果原鏈表中有 X 和 Y 兩個節(jié)點,其中 X.random --> Y 。那么在復制鏈表中對應的兩個節(jié)點 x 和 y ,同樣有 x.random --> y 。
返回復制鏈表的頭節(jié)點。
struct Node {
int val;
struct Node *next;
struct Node *random;
};

思路:
因為每個節(jié)點還有一個隨機指針,向拷貝標準單向鏈表的方式才處理,是有困難的;
第一步,先將拷貝的節(jié)點鏈在原節(jié)點后面

struct Node* cur = head;
while (cur)
{
struct Node* new = (struct Node*)malloc(sizeof(struct Node));
new->val = cur->val;
new->next = cur->next;
cur->next = new;
cur = new->next;
}
第二步,處理隨機指針,因為拷貝的就在原節(jié)點后面,拷貝的隨機指針就指向原節(jié)點隨機指針的后一個;

struct Node* cur = head;
while (cur)
{
struct Node* copy = cur->next;
if (cur->random == NULL)
{
copy->random = NULL;
}
else
{
copy->random = cur->random->next;
}
cur = copy->next;
}
第三步,將鏈表分開,并返回拷貝鏈表的頭;
程序:
struct Node* copyRandomList(struct Node* head)
{
if (head == NULL)
{
return NULL;
}
struct Node* cur = head;
while (cur)
{
struct Node* new = (struct Node*)malloc(sizeof(struct Node));
new->val = cur->val;
new->next = cur->next;
cur->next = new;
cur = new->next;
}
cur = head;
while (cur)
{
struct Node* copy = cur->next;
if (cur->random == NULL)
{
copy->random = NULL;
}
else
{
copy->random = cur->random->next;
}
cur = copy->next;
}
cur = head;
struct Node* copyHead = head->next ,*copy_n=copyHead->next,*copy=copyHead;
while (cur)
{
if (copy_n == NULL)
{
copy->next = NULL;
cur->next = NULL;
return copyHead;
}
else
{
cur->next = copy_n;
copy->next = copy_n->next;
}
cur = copy_n;
copy = copy_n->next;
copy_n = copy->next;
}
return copyHead;
}
到此這篇關于C語言數(shù)據(jù)結構之復雜鏈表的拷貝的文章就介紹到這了,更多相關C語言 數(shù)據(jù)結構內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VC中使用ADO開發(fā)數(shù)據(jù)庫應用程序簡明教程
這篇文章主要介紹了VC中使用ADO開發(fā)數(shù)據(jù)庫應用程序的方法,結合實例形式詳細講述了ADO的原理及VC使用ADO開發(fā)數(shù)據(jù)庫應用程序的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2016-06-06

