LeetCode 160. intersection list (the list to find two common node)

Topic links: https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

Write a program to find the starting node two single list intersect.

The following two lists:

 

Beginning at the intersection node c1.

 

Input: intersectVal = 8, listA = [ 4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 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.

Input: intersectVal = 2, listA = [ 0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 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.

Input: intersectVal = 0, listA = [ 2,6,4], listB = [1,5], skipA = 3, skipB = 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 skipA skipB may be any value.
Explanation: This two lists do not intersect, and therefore returns null.
 

note:

If there is no intersection of two lists, returns null.
After returning to the results, two lists must still maintain the original structure.
The entire list may be assumed that there is no cycle structure.
Try to meet program (n) time complexity of O, and only O (1) memory.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
 9     struct ListNode *pa=headA,*pb=headB;
10     int len1=0,len2=0,dist=0;
11     while(pa!=NULL){
12         len1++;
13         pa=pa->next;
14     }
15     while(pb!=NULL){
16         len2++;
17         pb=pb->next;
18     }
19     struct ListNode *longList,*shortList;
20     if(len1>len2){
21         longList=headA,shortList=headB;
22         dist=len1-len2;
23     }else{
24         longList=headB,shortList=headA;
25         dist=len2-len1;
26     }
27     while(dist--) longList=longList->next;
28     while(longList!=NULL){
29         if(longList==shortList) return longList;
30         longList=longList->next;
31         shortList=shortList->next;
32     }
33     return NULL;
34 }

 

Guess you like

Origin www.cnblogs.com/shixinzei/p/11408660.html