Skip to content

Instantly share code, notes, and snippets.

@jones
Created January 1, 2015 10:06
Show Gist options
  • Save jones/807883fdbf23915043e3 to your computer and use it in GitHub Desktop.
Save jones/807883fdbf23915043e3 to your computer and use it in GitHub Desktop.
Write a program to find the node at which the intersection of two singly linked lists begins.
/**
* 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) {
if(!headA || !headB) {
return NULL;
}
int lenA = getListLen(headA);
int lenB = getListLen(headB);
// Attempt to match the list heads
if (lenA > lenB) {
headA = advanceList(headA, lenA - lenB);
} else if (lenA < lenB) {
headB = advanceList(headB, lenB - lenA);
}
// Heads should be matched
while(headA != NULL && headB != NULL) {
if (headA == headB) {
return headA;
}
headA = headA->next;
headB = headB->next;
}
return NULL;
}
int getListLen(ListNode *head) {
int length = 0;
while(head) {
head = head->next;
length++;
}
return length;
}
ListNode *advanceList(ListNode *head, int len) {
for(int i = 0; i < len; i++){
head = head->next;
if (!head) {
return NULL;
}
}
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment