双指针-链表-面试题52. 两个链表的第一个公共节点
程序员文章站
2022-05-06 21:35:36
...
解题思路:
设交集链表长c,链表1除交集的长度为a,链表2除交集的长度为b,有
-
a + c + b = b + c + a
-
若无交集,则a + b = b + a
/**
* 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) {
ListNode h1=headA,h2=headB;
while(h1!=h2){
h1=h1==null?headB:h1.next;
h2=h2==null?headA:h2.next;
}
return h1;
}
}