1. 程式人生 > 其它 >【劍指offer】52. 兩個連結串列的第一個公共節點

【劍指offer】52. 兩個連結串列的第一個公共節點

劍指 Offer 52. 兩個連結串列的第一個公共節點

知識點:連結串列;

題目描述

輸入兩個連結串列,找出它們的第一個公共節點。

如下面的兩個連結串列:

示例

示例1:

輸入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
輸出:Reference of the node with value = 8
輸入解釋:相交節點的值為 8 (注意,如果兩個列表相交則不能為 0)。從各自的表頭開始算起,連結串列 A 為 [4,1,8,4,5],連結串列 B 為 [5,0,1,8,4,5]。在 A 中,相交節點前有 2 個節點;在 B 中,相交節點前有 3 個節點。

示例2:

輸入:intersectVal= 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
輸出:Reference of the node with value = 2
輸入解釋:相交節點的值為 2 (注意,如果兩個列表相交則不能為 0)。從各自的表頭開始算起,連結串列 A 為 [0,9,1,2,4],連結串列 B 為 [3,2,4]。在 A 中,相交節點前有 3 個節點;在 B 中,相交節點前有 1 個節點。

解法一:解析

我們可以假設連結串列A獨有部分長度為m,連結串列B獨有部分長度為n,兩個連結串列相交部分長度為x,所以連結串列A的長度為m+x,連結串列B的長度為n+x。我們定義兩個指標從兩個連結串列同時走,A走完後去走B,B走完後去走A,兩者速度相同,最後到達相交點處正好碰面。走的距離都是m+n+x;

/**
 * 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 tempA = headA;
        ListNode tempB = headB;
        while(tempA != tempB){
            //A走到頭就接到B上;
            tempA = tempA != null ? tempA.next : headB;
            //B走到頭就接到A上;
            tempB = tempB != null ? tempB.next : headA;
        }
        return tempB;
    }
}

時間複雜度:O(N);
空間複雜度:O(1);