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.
It's easy if you don't ask for this question. You can do it with hashset.
But the topic requires in O (n) time and use only O (1) memory.
You can traverse two linked lists to make their lengths as long as possible. And then compare them one by one.
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) { - inta=0, b = 0; theListNode Tempa =Heada; -ListNode TEMPB =headb; - while(Tempa! =NULL) { -++A; +Tempa =Tempa.next; - } + while(TEMPB! =NULL) { A++b; atTEMPB =Tempb.next; - } -Tempa =Heada; -TEMPB =headb; - while(A >b) { ---A; inTempa =Tempa.next; - } to while(B >a) { +--b; -TEMPB =Tempb.next; the } * while(Tempa! =NULL) { $ if(Tempa = =TEMPB) {Panax Notoginseng returnTempa; -}Else { theTempa =Tempa.next; +TEMPB =Tempb.next; A } the } + return NULL; - } $}
Leetcode intersection of the Linked Lists