复杂链表的复制。一个链表的每个节点,有一个指向next指针指向下一个节点,还有一个random指针指向这个链表中的一个随机节点或者NULL,现在要求实现复制这个链表,返回复制后的新链表。
typedef struct SListNode
{
int data;//值
struct SListNode *next;//下一节点的指针
struct SListNode *random;//可以指向任意节点,也可以指向空
}SListNode;
解: 思路:首先要复制原链表的每一个节点,把复制的每一个节点插在原节点的后面。
然后开始对random处理,新的random所指的节点就是原节点random所指的节点的下一个。
最后就是分离俩个链表,新的链表复制成功。
源程序:
#include <stdio.h>
#include <malloc.h>
#include <Windows.h>
typedef struct SListNode
{
int data;//值
struct SListNode *next;//下一节点的指针
struct SListNode *random;//可以指向任意节点,也可以指向空
}SListNode;
SListNode * BuyNode(int date)//创建一个新节点
{
SListNode *n=(SListNode*)malloc(sizeof(SListNode));
n->data=date;
n->next=NULL;
n->random=NULL;
return n;
}
SListNode *SListCopy(SListNode *list)
{
SListNode *cur=list;
SListNode *newlist=NULL;
if (cur==NULL)
{
return cur;
}
else if (cur->next==NULL)
{
return BuyNode(cur->data);
}
while (cur)//复制链表
{
SListNode *Newnode=BuyNode(cur->data);
Newnode->next=cur->next;
cur->next=Newnode;
cur=cur->next->next;
}
cur=list;
while(cur)//置random
{
SListNode *Next=cur->next;
if(cur->random)
Next->random=cur->random->next;
cur=Next->next;
}
newlist=list->next;
cur=list->next;
while (cur->next)//分离链表
{
cur->next=cur->next->next;
cur=cur->next;
}
cur->next=NULL;
return newlist;
}
void Print(SListNode* plist)//打印链表
{
SListNode* cur = plist;
while(cur)
{
printf("%d->", cur->data);
cur = cur->next;
}
printf("NULL\n");
}
void test() //测试代码
{
SListNode* newlist=NULL;
SListNode* node1 = BuyNode(1);
SListNode* node2 = BuyNode(2);
SListNode* node3 = BuyNode(3);
SListNode* node4 = BuyNode(4);
SListNode* node5 = BuyNode(5);
node1->next = node2;
node1->random = node3;
node2->next = node3;
node2->random = node1;
node3->next = node4;
node3->random = NULL;
node4->next = node5;
node4->random = node5;
node5->random = node5;
Print(node1);
newlist = SListCopy(node1);
Print(newlist);
}
int main()
{
test();
system("pause");
}