1、判断两个链表是否相交
如果两个链表相交,则输出此交点的值
//构造交点
bool Makepoint(List plist1,List plist2 ,int e)
{
Node* p = plist1->next;
Node* s = plist2->next;//形成环的点
Node* tail;//最后一个结点
int a = Getlength(plist1);
int b = Getlength(plist2);
if (a > b)
{
while (a > b)
{
p = p->next;
a--;
}
}
else if (a < b)
{
while (a < b)
{
s = s->next;
b--;
}
}
while (p->next != NULL&&s->next!=NULL)
{
if (p->data == e&&s->data==e)//找到指定结点
s ->next=p;
p = p->next;
s = s->next;
}
return true;
}
//求两个链表的交点
Node* Point(List plist1, List plist2)
{
assert(plist1 != NULL);
assert(plist2 != NULL);
if (plist1 == NULL||plist2==NULL)
return NULL;
Node* p = plist1->next;
Node* q = plist2->next;
int a = Getlength(plist1);
int b = Getlength(plist2);
if (a > b)
{
while (a > b)
{
p = p->next;
a--;
}
}
else if (a < b)
{
while (a < b)
{
q = q->next;
b--;
}
}
while (p != NULL && q != NULL)
{
if (p== q)
return p;
p = p->next;
q = q->next;
}
return NULL;
}
测试:
int main()
{
Node head1;
InitList(&head1);
for (int i = 0; i < 10; i++)
{
Insert_tail(&head1, i);
}
//Show(&head1);
Node head2;
InitList(&head2);
for (int j = 0; j < 8; j++)
{
Insert_tail(&head2,j);
}
Insert(&head1, 7, 3);
Show(&head1);
Show(&head2);
Makepoint(&head1, &head2, 3);
Node*p=Point(&head1, &head2);
if (p == NULL)
{
printf("两个链表没有交点!\n");
}
else
{
printf("两个链表的交点为:%d\n", p->data);
}
return 0;
}
运行结果:
2、输出有环链表进入环的第一个结点
//输出有环链表进入环的第一个结点
Node* IsCyclepoint(List plist)
{
assert(plist != NULL);
if (plist == NULL)
return NULL;
//设置快慢指针,一个走两步,一个走一步
Node* p = plist->next;
Node* q = plist->next->next;
while (q != NULL && q->next != NULL)
{
if (p == q)
{
break;
}
p = p->next;
q = q->next->next;
}
if (q == NULL || q->next == NULL)//无环
{
return NULL;
}
Node* s = plist;
while (s != p)
{
s = s->next;
p = p->next;
}
return s;
}
测试:
int main()
{
Node head;
InitList(&head);
for (int i = 0; i < 20; i++)
{
//Insert_head(&head, i);
Insert_tail(&head, i);
}
int len = Getlength(&head);
printf("len=%d\n", len);
Show(&head);
//创建一个有环链表
//IsCycle(&head);
Node *s = Search(&head, 3);
Node* q = Search(&head, 9);
q->next = s;
IsCycle(&head);
Node* p = IsCyclepoint(&head);
if (p == NULL)
{
printf("无环!\n");
}
else
{
printf("进入环的第一个结点为:%d\n", p->data);
}
return 0;
}
运行结果: