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.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A Public classSolution { - PublicListNode Getintersectionnode (ListNode heada, ListNode headb) { - if(Heada = =NULL|| HEADB = =NULL)return NULL; theListNode CA = Heada, cb =headb; - intCnta = 0, CNTB = 0; - while(CA! =NULL){ -cnta++; +CA =Ca.next; - } + while(CB! =NULL){ Acntb++; atCB =Cb.next; - } - intSub = Math.Abs (Cnta-CNTB); - if(Cnta >CNTB) { - while(Sub > 0){ -Heada =Heada.next; insub--; - } to}Else{ + while(Sub > 0){ -HEADB =Headb.next; thesub--; * } $ }Panax Notoginseng while(Heada! =headb) { -Heada =Heada.next; theHEADB =Headb.next; + } A returnHeada; the } +}
Intersection of Linked Lists Java Solutions