160. Intersection of Two Linked Lists

/** * 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) { int counta = 0, countb = 0; ListNode * ptra = headA; while(ptra != nullptr){ counta++; ptra = ptra->next; } ListNode * ptrb = headB; while(ptrb != nullptr){ countb++; ptrb = ptrb->next; } // reset ptrb and ptra ptrb = headB; ptra = headA; if (counta > countb){ int diff = counta-countb; while(diff-- != 0) ptra = ptra->next; } else { int diff = countb-counta; while(diff-- != 0) ptrb = ptrb->next; } // begin compare while(ptra != nullptr){ if (ptra == ptrb) return ptra; else { ptra = ptra->next; ptrb = ptrb->next; } } return nullptr; } };
The idea is to get the count first, then shift the pointers so that they start together...

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.