复杂链表的复制

来源:互联网 发布:c语言中百分之f 编辑:程序博客网 时间:2024/05/16 17:48

复杂链表的结构

struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};

//其中random指向链表中的任意一个节点或者为空

要在o(n)时间内完成链表的复制,就要求每遍历一个节点就要能确定复制链表的random指针地址而实际上对于原始链表的每一个节点我们能确定对应的random指针地址。难点在于如何通过原始指针的random指针地址确定复制指针对应的random指针。本题思路:对链表中的每个节点进行复制,并将其插入到原始节点的后面,这样就能通过原始节点找到对应的复制节点,实现在0(1)的时间内找到复制节点的位置。

代码如下:

// ConsoleApplication13.cpp : 定义控制台应用程序的入口点。
/*复杂链表的复制
  
*/
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
RandomListNode* CreateNode(int nValue)
{
RandomListNode* pNode = new RandomListNode(nValue);
return pNode;
}


void BuildNodes(RandomListNode* pNode, RandomListNode* pNext, RandomListNode* pSibling)
{
if (pNode != NULL)
{
pNode->next = pNext;
pNode->random = pSibling;
}
}


//复制链表
void CloneNode(RandomListNode* Phead){
RandomListNode* Pnode = Phead;
while (Pnode){
RandomListNode* clonenode=new RandomListNode(Pnode->label);
clonenode->next = Pnode->next;
Pnode->next = clonenode;
Pnode = clonenode->next;




}
}
//修改复制链表random指针
void ChangeRandomPointer(RandomListNode* phead){
RandomListNode *p, *q;
p = phead;
while (p){
q = p->random;
cout << p->label << endl;
if (q){
p->next->random = q->next;
}

p = p->next->next;

}
}
//拆分原始链表及复制表
RandomListNode* Solution(RandomListNode* phead){
RandomListNode *p, *q, *Clonehead;
p = phead;
Clonehead = p->next;
q = Clonehead;
while (p){
p->next = q->next;
if (p->next){
q->next = p->next->next;
}

p = p->next;
q = q->next;
}
return Clonehead;
}
RandomListNode* Clone(RandomListNode* phead){
CloneNode(phead);
ChangeRandomPointer(phead);
return Solution(phead);
}

//          -----------------
//         \|/              |
//  1-------2-------3-------4-------5
//  |       |      /|\             /|\
//  --------+--------               |
//          -------------------------
int _tmain(int argc, _TCHAR* argv[])
{
RandomListNode* pNode1 = CreateNode(1);
RandomListNode* pNode2 = CreateNode(2);
RandomListNode* pNode3 = CreateNode(3);
RandomListNode* pNode4 = CreateNode(4);
RandomListNode* pNode5 = CreateNode(5);


BuildNodes(pNode1, pNode2, pNode3);
BuildNodes(pNode2, pNode3, pNode5);
BuildNodes(pNode3, pNode4, NULL);
BuildNodes(pNode4, pNode5, pNode2);
RandomListNode* head= Clone(pNode1);
cout << head->random->next->label << endl;
system("pause");
return 0;
}


0 0
原创粉丝点击