单链表的面试题2

时间:2022-06-17 09:41:43

复制复杂链表
复杂链表:⼀个链表的每个节点,有⼀个指向next指针指向下⼀个节 点,还有⼀个random指针指向这个链表中的⼀个随机节点或者NULL
思路如下
单链表的面试题2
头文件

#ifndef __LINK_LIST_H__
#define __LINK_LIST_H__
typedef int DataType;

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct ComplexNode
{
DataType _data;//数据域
struct ComplexNode* _next;//指向下一个结点的指针
struct ComplexNode *_random;//指向链表中随机的结点
}ComplexNode;
//定义一个复杂链表
//复杂链表的输出
void printfcomplex(ComplexNode *complexlist);
//复杂链表的复制
ComplexNode * copycomplexlist(ComplexNode * head);

功能函数

void printfcomplex(ComplexNode *complexlist)//复杂链表的输出
{
ComplexNode * cur = NULL;
cur = complexlist;
while (cur)
{
if (cur->_random)
{
printf("[%d]->%d ", cur->_data, cur->_random->_data);
}
else
{
printf("[%d]->%d ",cur->_data,NULL);
}
cur=cur->_next;
}
printf("\n");
}
//复杂链表的复制
ComplexNode * copycomplexlist(ComplexNode * head)
{
ComplexNode *cur = NULL;
ComplexNode *copy= NULL;
ComplexNode *pre1= NULL;
ComplexNode *pre2 = NULL;
ComplexNode *tmp = NULL;
ComplexNode *newnode = NULL;
cur = head;
//将当前结点拷贝一份,插入到当前结点的下一个位置
while (cur)
{
ComplexNode *newnode = (ComplexNode*)malloc(sizeof(ComplexNode));
newnode->_data = cur->_data;
newnode->_next = cur->_next;
cur->_next = newnode;
newnode->_random = NULL;
cur = cur->_next->_next;
}
//调整random 指针
tmp = head;
copy = head->_next;
while (tmp!=NULL)//当tmp的最后一个结点为空时,不再赋值
{
copy->_random = tmp->_random->_next;
tmp = copy->_next;
if (tmp != NULL)//最后一次结点为空,不再让copy往后移动
{
copy = tmp->_next;
}
}
//断开next指针
pre1= head;
pre2 = head->_next;
newnode = head->_next;
while (pre1)
{
pre1->_next = pre2->_next;
pre1 = pre1->_next;
if (pre1 != NULL)
{
pre2->_next = pre1->_next;
pre2 = pre2->_next;
}
}
return newnode;
}

测试函数

void test4()
{
ComplexNode *head;
ComplexNode*head1;
ComplexNode *p1 = Buynewnode(1);//为每一个结点动态开辟内存
ComplexNode *p2 = Buynewnode(2);
ComplexNode *p3 = Buynewnode(3);
ComplexNode *p4 = Buynewnode(4);
head = p1;
p1->_next = p2;//为每一个结点的nest和random指向值
p1->_random = p4;
p2->_next = p3;
p2->_random = p3;
p3->_next = p4;
p3->_random = p1;
p4->_next = NULL;
p4->_random = p2;
printfcomplex(head);//复杂链表的输出
head1=copycomplexlist(head);//复制单链表
printfcomplex(head1);
}
int main()
{
test4();//测试复杂链表的复制
return 0;
}

结果显示
单链表的面试题2