public class 相交链表_09 {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int lengthA = 0, lengthB = 0;
ListNode i = headA;
ListNode j = headB;
//求出A长B的长度
while (i != null) {
i = i.next;
lengthA++;
}
while (j != null) {
j = j.next;
lengthB++;
}
//使A和B的还未相交的长度相等
while (lengthB > lengthA) {
headB = headB.next;
lengthB--;
}
while (lengthB < lengthA) {
headA = headA.next;
lengthA--;
}
//遍历链表A或B,如果相同的第N个节点相等时,则该点为相交交点
//如果遍历结束,未找到匹配节点,返回null
while (headA != null) {
if (headA == headB)
return headA;
headA = headA.next;
headB = headB.next;
}
return null;
}
}
相交链表
最新推荐文章于 2024-12-05 23:24:17 发布