判断两个链表相交的交点
时间: 2023-12-04 09:02:47 浏览: 132
可以使用双指针法求解。首先遍历两个链表,得到它们的长度。然后让长的链表先走多出的长度,让两个链表剩下的长度相等。最后同时遍历两个链表,找到相同的节点即为它们的交点。如果没有相交的节点,就返回 null。
下面是 Java 代码实现:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int lenA = getLength(headA);
int lenB = getLength(headB);
ListNode curA = headA;
ListNode curB = headB;
if (lenA > lenB) {
int diff = lenA - lenB;
while (diff > 0) {
curA = curA.next;
diff--;
}
} else if (lenB > lenA) {
int diff = lenB - lenA;
while (diff > 0) {
curB = curB.next;
diff--;
}
}
while (curA != null && curB != null) {
if (curA == curB) {
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;
}
private int getLength(ListNode node) {
int count = 0;
while (node != null) {
count++;
node = node.next;
}
return count;
}
}
阅读全文