Write a program to find the node at which the intersection of the singly linked lists begins.
For example, the following, linked lists:
A: a1→a2 c1→c2→c3 B: b1→b2→b3
Begin to intersect at node C1.
Notes:
- If The linked lists has no intersection at all, return
null
.
- The linked lists must retain their original structure after the function returns.
- You may assume there is no cycles anywhere in the entire linked structure.
- Your code should preferably run in O (n) time and use only O (1) memory. can only be O (n) time complexity, here is the practice is to first traverse two linked list to know the length, and then let the long list first walk, then 22 comparison, Time complexity O (lengtha+lengthb+maxlength) is O (n)
/** * 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) {if (HeadA = = NULL | | HEADB = = null) {return null; } int lengtha = 1; int LENGTHB = 1; ListNode *afirst = Heada; ListNode *bfirst = headb; while (Afirst->next) {lengtha++; Afirst = afirst->next; } while (Bfirst->next) {lengthb++; Bfirst = bfirst->next; } if (Afirst! = bfirst) {return NULL; } int length = lengtha;//< random Initialization of an if (Lengtha > LENGTHB) {int diff = LENGTHA-LENGTHB ; length = LENGTHB; while (diff--) {Heada = heada->next; }} if (Lengtha < LENGTHB) {length = Lengtha; int diff = Lengthb-lengtha; while (diff--) {headb = headb->next; }} while (length--) {if (Heada = = headb) {return heada; } Heada = heada->next; HEADB = headb->next; } return NULL; }};
Leetcode-intersection of two Linked Lists find the intersection of two linked lists, let the long list go first