C 链表交点程序的改进
我已经写了下面的代码来查找链接列表的交点。 有没有人能回顾一下,告诉我有没有什么可以改进的地方 算法-:C 链表交点程序的改进,c,linked-list,C,Linked List,我已经写了下面的代码来查找链接列表的交点。 有没有人能回顾一下,告诉我有没有什么可以改进的地方 算法-: 分别在LL-1和LL-2的头部初始化两个指针p1和p1。然后让它们都遍历列表,一次遍历一个节点 当p1到达列表末尾时,将其重定向到LL-2的头部;当p2到达列表末尾时,将其重定向到LL-1的头部 如果在任何点p1与p2相交,则p1/p2为交点 int getIntesectionNode(struct Node* head1, struct Node* head2) { struct N
int getIntesectionNode(struct Node* head1, struct Node* head2)
{
struct Node *start1 = head1;
struct Node *start2 = head2;
bool endFound1 = false;
bool endFound2 = false;
if( start1 == NULL || start2 == NULL)
{
return -1;
}
while(1)
{
start1 = start1->next;
start2 = start2->next;
if( start1 != start2)
{
if( start1 == NULL)
{
if (endFound1)
{
printf("Intersection not found !");
break;
}
start1 = head2;
endFound1 = true;
}
if( start2 == NULL)
{
if (endFound2 )
{
printf("Intersection not found !");
break;
}
start2 = head1;
endFound2 = true;
}
}
else
{
printf("Intersection point found\n");
printf("%d",start1->data);
return start1->data;
}
}
return -1;
}
我想我不明白,但如果你按照我想的做,我会使用第二个循环, 并检查每个LL-2的所有LL-1。我还要检查平等的起点
在开始循环并转到下一点之前,在循环之前不要检查它。您的问题是什么?你的代码有效吗?如果没有,您会得到什么错误?或者输出与您想要的有什么不同?它工作正常,但我想检查是否有任何改进可以使其更好。如果有两个长度为N的列表,终止条件是什么?假设列表中的所有元素都是不同的,那么这些列表中的指针永远不会相交。如果任一列表的尾部都有一个循环,则不能保证有一个交点;这取决于第二个指针到达循环时两个指针的位置。如果两个列表的尾部都有一个循环,那么可以保证指针不会相交。(旁白:用换行符结束打印格式是一个好主意——你的许多格式末尾没有换行符。)