Find the difference in the length of both the lists
Then start checking the equality for the nodes
Once we find equal node return that node
otherwise if we reach at the end return the null
There is a better way to do it:
We are going to traverse the shorter one and longer one at the same time
We are going to set pointers to the heads of both of these.
When we get at the end of the shorter one, we set the pointer to the head of the longer one.
When we get at the end of the longer one, we set the pointer to the head of the shorter one.
Here, is the code of the implementation
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == NULL|| headB == NULL) return NULL;
ListNode*a_pointer = headA;
ListNode*b_pointer = headB;
//while the nodes are not equal
while(a_pointer != b_pointer ){
if(a_pointer == NULL){
//this means it is at the end of the list
a_pointer = headB;
}
else{
a_pointer = a_pointer->next;
}
if(b_pointer == NULL){
//this means it is at the end of the list
b_pointer = headA;
}
else{
b_pointer = b_pointer->next;
}
}
return a_pointer;
}
};
Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices
Top comments (0)