编写一个程序,找到两个单链表相交的起始节点。
思路:
遍历链表1,得到长度
遍历链表2,得到长度
求链表差值
让长的链表先走差值步
一起遍历,找到相同元素
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null || pHead2==null)
return null;
int count1=0;
ListNode head1=pHead1;
while(head1!=null)
{
count1++;
head1=head1.next;
}
int count2=0;
ListNode head2=pHead2;
while(head2!=null)
{
count2++;
head2=head2.next;
}
int flag=count1-count2;
if(flag>0)
{
while(flag>0)
{
pHead1=pHead1.next;
flag--;
}
while(pHead1!=pHead2)
{
pHead1=pHead1.next;
pHead2=pHead2.next;
}
}
else{
while(flag<0)
{
pHead2=pHead2.next;
flag++;
}
while(pHead1!=pHead2)
{
pHead1=pHead1.next;
pHead2=pHead2.next;
}
}
return pHead1;
}
}
本文介绍了一种算法,用于查找两个单链表的首个相交节点。通过测量两个链表的长度差,并让较长链表先前进相应步数,然后同步遍历,直至找到第一个相同节点。

被折叠的 条评论
为什么被折叠?



