2
* Definition for singly-linked list.6
* ListNode(int x) : val(x), next(NULL) {}11
// function to get length of linked list12
int getLength(ListNode *head) {16
while (head != NULL) {23
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {24
// ptr1 & ptr2 will move to check nodes are intersecting or not25
// ptr1 will point to the list which have higher length, higher elements26
// (big list) ptr2 will point to small list27
ListNode *ptr1, *ptr2;29
// fetching length of both the list,as we want a node that both ptr points30
// simultaneously so if both list have same length of nodes, they travel31
// with same speed, they intersect if diff legths, it'll be difficult for us32
// to catch so by substracting list with higher length with lower length we33
// get same level of length, from which both ptr start travaeling, they may35
int length1 = getLength(headA);36
int length2 = getLength(headB);40
// ptr1 points to longer list41
if (length1 > length2) {42
diff = length1 - length2;47
diff = length2 - length1;52
// till diff is zero and we reach our desired posn54
// incrementing ptr1 so that it can be at a place where both list have66
// traverse both pointers together, till any of them gets null67
while ((ptr1 != NULL) && (ptr2 != NULL)) {68
// at any point, both point to same node return it73
// increment both pointers, till they both be NULL78
// if not found any intersaction, return null