LeetCode160 - intersect list

Title Description
Write a program to find the starting node two single list intersect.
The following two lists:
Here Insert Picture Description
Example 1:
Here Insert Picture Description
Input: intersectVal = 8, listA = [ 4,1,8,4,5], listB = [5,0,1,8,4,5], skiha = 2, skihb = 3
output: Reference of the node with value = 8
input interpretation: intersection node is 8 (note, if the two intersecting listing can not be 0). From the respective header start date, list A is [4,1,8,4,5], B is a chain [5,0,1,8,4,5]. In A, the first intersection node has two nodes; in B, there are three nodes before the intersection node.
Example 2:

Input: intersectVal = 2, listA = [ 0,9,1,2,4], listB = [3,2,4], skiha = 3, skihb = 1
Output: Reference of the node with value = 2
input interpretation: intersection node is 2 (note that, if it can not intersect the two lists is 0). From the respective header start date, list A is [0,9,1,2,4], list B is [3,2,4]. In A, the first intersection node has three nodes; in B, there is an intersection node before the node.
Example 3:
Here Insert Picture Description
Input: intersectVal = 0, listA = [ 2,6,4], listB = [1,5], skiha = 3, skihb = 2
Output: null
Input interpretation: from the respective header start date, list A is [2,6,4], B is a chain [1,5]. Since these two lists do not intersect, it intersectVal must be 0, and the skiha skihb may be any value.
Explanation: This two lists do not intersect, and therefore returns null.

Solution: double pointer (C ++)

The idea of the algorithm is very simple:
initialize ha = headA, hb = headB, traversing.
If the short A chain, ha will first reach the end of the list, when it reaches the end ha, ha is reset headB; Similarly, when hb reaches the end, hb is reset headA. When ha and hb encounter is inevitable intersection of two lists.

Why do you can do it?
Because such a traversal of ha, the distance traveled is the a + c + b, in terms of hb, i.e. b + c + a, apparently a + c + b = b + c + a, this is the core principle of the algorithm.

Here Insert Picture Description

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *ha = headA, *hb = headB;
        while(ha != hb)
        {
            ha = ha==NULL?headB:ha->next;
            hb = hb==NULL?headA:hb->next;
        }
        return ha;
    }
};
Published 152 original articles · won praise 22 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_38204302/article/details/105122358