链表面试题---复杂链表的复制

 

复杂链表  : 在复杂链表中,每个节点除了有一个next指向下一节点外,还有一个random指向任意节点或者NULL

    链表面试题---复杂链表的复制_第1张图片

 

链表面试题---复杂链表的复制_第2张图片

代码如下 :

Linklist.h  头文件

#ifndef __LINKLIST_H__
#define __LINKLIST_H__

#include 
#include 
#include 

//定义元素类型
typedef int DataType;
//复杂链表的定义
typedef struct ComplexNode
{
	DataType data;
	struct ComplexNode* next;     //存放下一个节点
	struct ComplexNode* random;  //存放任意节点
}ComplexNode;
//申请节点
ComplexNode *BuyComplexNode(DataType x);
//复杂链表的复制
ComplexNode *CopyComplexList(ComplexNode* plist);
//复杂链表的打印
void PrintComplexList(ComplexNode* plist);


#endif __LINKLIST_H__

Linklist.c 主函数文件

#include "Linklist.h"

//申请节点
ComplexNode* BuyComplexNode(DataType d)
{
	ComplexNode* node = (ComplexNode *)malloc(sizeof(ComplexNode));
	if (node == NULL)
	{
		perror("Buy Node");
		exit(FILENAME_MAX);
	}
	node->data = d;
	node->next = NULL;
	node->random = NULL;
	return node;
}
//复杂链表的打印
void PrintComplexList(ComplexNode* plist)
{
	assert(plist);
	while (plist)
	{
		printf("%d : ", plist->data);
		if (plist->random != NULL)
		{
			printf("(%d)-->", plist->random->data);
		}
		else
		{
			printf("(NULL)-->");
		}
		plist = plist->next;
	}
	printf("Over !\n");
}
//复杂链表的复制
ComplexNode* CopyComplexList(ComplexNode* plist)
{
	ComplexNode* cur = NULL;
	ComplexNode* tmp = NULL;
	ComplexNode* head = NULL;
	assert(plist);
	cur = plist;
	while (cur != NULL)
	{
		tmp = BuyComplexNode(cur->data);
		tmp->next = cur->next;
		cur->next = tmp;
		cur = tmp->next;
	}
	cur = plist;
	tmp = cur->next;
	while (cur != NULL)
	{
		if (cur->random != NULL)
		{
			tmp->random = cur->random->next;
		}
		cur = tmp->next;
		if (cur != NULL)
		{
			tmp = cur->next;
		}
	}
	cur = plist;
	tmp = cur->next;
	head = tmp;
	while (cur != NULL)
	{
		cur->next = tmp->next;
		cur = cur->next;
		if (cur != NULL)
		{
			tmp->next = cur->next;
		}
		tmp = tmp->next;
	}
	return head;
}

test.c 测试文件

#include "Linklist.h"
void testCopyComplexList()
{
	ComplexNode * cur;
	ComplexNode * plist;
	ComplexNode * p1 = BuyComplexNode(5);
	ComplexNode * p2 = BuyComplexNode(4);
	ComplexNode * p3 = BuyComplexNode(3);
	ComplexNode * p4 = BuyComplexNode(2);
	ComplexNode * p5 = BuyComplexNode(1);
	plist = p1;
	p1->next = p2;
	p2->next = p3;
	p3->next = p4;
	p4->next = p5;
	p1->random = p3;
	p2->random = p5;
	p3->random = NULL;
	p4->random = p1;
	p5->random = p2;
	PrintComplexList(plist);
	cur = CopyComplexList(plist);
	PrintComplexList(plist);
}
int main()
{
 testCopyComplexList();
 system("pause");
 return 0;
}

 

你可能感兴趣的:(数据结构)