雙指針-鏈表-面試題52. 兩個鏈表的第一個公共節點

解題思路:

設交集鏈表長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;  
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章