相交链表
160. 相交链表
思路:lenA + lenB = lenB + lenA,那么两条链表分别走一遍之后,如果无环,那么 curA 始终不等于 curB,否则第一次相交节点即为两条链表相交的起始节点(确保后半程距离相同)。
关于环:其实有环也没啥了不起,无非是多一层链表长度的计算,使得两者走的路程变成「有限」的路程(入口到首结点距离 + 环长)
/**
* 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) {
if(headA == null || headB == null) return null; // 特判
ListNode curA = headA;
ListNode curB = headB;
while(true) {
while(curA != null && curB != null) {
if(curA == curB) return curA;
curA = curA.next;
curB = curB.next;
}
if(curA == null && curB == null) break; // null
if(curA == null) curA = headB;
if(curB == null) curB = headA;
}
return null;
}
} 