
思路:
两个链表相交,尾节点必然相等
#include <stdio.h>
#include <stdlib.h>
struct list
{
int element;
struct list *next;
};
//
//问题:判断两个链表是否相交
//思路:若两个链表相交,则两个链表的尾节点必然相等
//
int func01(struct list *A , struct list *B)
{
struct list *pa = A;
struct list *pb = B;
while(pa != nullptr)
{
pa = pa->next;
}
while(pb != nullptr)
{
pb = pb->next;
}
return (pa->element == pb->element);
}
//
//问题:判断链表是否有环
//思路:通过双指针判断,一前一后,前快后慢,若有环
//快的可以追上慢的
//
int func02(struct list *A)
{
struct list *fast = nullptr;
struct list *slow = nullptr;
if(A->next == nullptr)
{
return 0;
}
fast = A->next->next;
slow = A->next;
while(fast != nullptr && slow != nullptr)
{
if(fast->element == slow->element)
{
return 1;
}
fast = fast->next;
slow = slow->next;
}
return 0;
}
int main()
{
printf("Hello world!
");
return 0;
}
时间复杂度O(nlistA+nlistB)