- 常规方法
/**
* 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 len1 = getLength(headA), len2 = getLength(headB);
while(len1 > len2) {
headA = headA.next;
len1--;
}
while(len1 < len2) {
headB = headB.next;
len2--;
}
while(headA != headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
private int getLength(ListNode head) {
int length = 0;
while(head != null) {
head = head.next;
length++;
}
return length;
}
}
- 热评大佬
https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode 题解 - 链表.md
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode l1 = headA, l2 = headB;
while (l1 != l2) {
l1 = (l1 == null) ? headB : l1.next;
l2 = (l2 == null) ? headA : l2.next;
}
return l1;
}