题目描述
编写一个程序,找到两个单链表相交的起始节点。
注意:
如果两个链表没有交点,返回 null.
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
思路分析
题目假设链表无环。先判断是否相交,相交则根据两链表的长度差距,知道较长的链表,让长的链表先走len长度,之后两条一起走,相交点就是所求。
代码实现
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode curA = headA, curB = headB;
int len = 0;
while (curA != null) {
len++;
curA = curA.next;
}
while (curB != null) {
len--;
curB = curB.next;
}
if (curA != curB) {
return null;
}
//两链表相交
//A放长,B放短
curA = len > 0 ? headA : headB;
curB = curA == headA ? headB : headA;
len = Math.abs(len);
//长的先走
while (len-- > 0) {
curA = curA.next;
}
//同时走
while (curA != curB) {
curA = curA.next;
curB = curB.next;
}
return curA;
}