题目链接点击打开链接
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lengthA=0;
ListNode temp=headA;
while(temp!=null)
{
temp=temp.next;
lengthA++;
}
int lengthB=0;
temp=headB;
while(temp!=null)
{
temp=temp.next;
lengthB++;
}
ListNode APoint=headA;
ListNode BPoint=headB;
int diff=lengthA-lengthB;
while(diff>0)
{
APoint=APoint.next;
diff-=1;
}
while(diff<0)
{
BPoint=BPoint.next;
diff+=1;
}
while(APoint!=BPoint)
{
APoint=APoint.next;
BPoint=BPoint.next;
}
return APoint;
}
}
本文介绍了一种寻找两个单链表相交节点的方法。通过计算两链表长度差并同步遍历指针来定位交点,实现了高效查找。适用于解决链表数据结构问题。
1039

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



