#include <iostream>
#include<cstdlib>
using namespace std;
//判断单链表是否有环
Node* getLoopNode(Node *head)
{
if(NULL == head || NULL == head->next || NULL == head->next->next)
return NULL;
Node *n1 = head->next;//慢节点走一步
Node *n2 = head->next->next;//快节点走两步
while(n1 != n2)
{
if(NULL == n2->next || NULL == n2->next->next)
return NULL;//快节点走空则无环
n2 = n2->next->next;
n1 = n1->next;
}
n2 = head;//快慢节点相遇后,快指针指向头节点
while(n1 != n2)
{
n1 = n1->next;
n2 = n2->next;
}
return n1;//返回入环节点
}
//不带环的链表的相交节点
Node* noLoop(Node *head1,Node *head2)
{
if(NULL == head1 || NULL == head2)
return NULL;
Node *cur1 = head1;
Node *cur2 = head2;
int n = 0;
while(NULL != cur1->next)
{
n++;
cur1 = cur1->next;
}
while(NULL != cur2->next)
{
n--;
cur2 = cur2->next;
}
if(cur1 != cur2) //若最后一个节点不想等,则俩链表不相交
return NULL;
cur1 = n > 0 ? head1 : head2;
cur2 = cur1 == head1 ? head2 : head1;//cur1为较长链表
n = abs(n);
while(0 != n) //以较短的那个链表为准
{
n--;
cur1 = cur1->next;
}
while(cur1 != cur2)
{
cur1 = cur1->next;
cur2 = cur2->next;
}
return cur1;
}
//带环链表的相交节点的判断
Node* bothLoop(Node *head1,Node *loop1,Node *head2,Node *loop2)
{
Node *cur1,*cur2;
if(loop1 == loop2) //与不带环的相交节点的判断一样的
{
cur1 = head1;
cur2 = head2;
int n = 0;
while(cur1 != loop1)
{
n++;
cur1 = cur1->next;
}
while(cur2 != loop2)
{
n--;
cur2 = cur2->next;
}
cur1 = n > 0 ? head1 : head2;
cur2 = cur1 == head1 ? head2 : head1;
n = abs(n);
while(0 != n)
{
n--;
cur1 = cur1->next;
}
while(cur1 != cur2)
{
cur1 = cur1->next;
cur2 = cur2->next;
}
return cur1;
}
else
{
cur1 = loop1->next;
while(cur1 != loop1)
{
if(cur1 == loop2)
return loop2;
cur1 = cur1->next;
}
return NULL;
}
}
int main()
{
//两个都没环
if((getLoopNode(head1)==Null)&&(getLoopNode(head2)==Null))
{
if(noLoop(head1,head2)==Null)
printf("没有相交\n");
else
{
//noLoop(head1,head2)返回节点就是相交节点
}
}
//两个都有环
else if((getLoopNode(head1)!=Null)&&(getLoopNode(head2)!=Null))
{
if(bothLoop(head1,getLoopNode(head1),head2,getLoopNode(head2))==Null)
printf("没有相交\n");
else
{
//bothLoop(head1,getLoopNode(head1),head2,getLoopNode(head2)返回节点就是相交节点
}
}
//一个有环一个没环一定不相交
else
{
printf("没有相交\n");
}
return 0;
}
单向链表相交问题
最新推荐文章于 2022-12-09 16:29:03 发布