Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save icameling/fc7e55c717e4a1db8079da9fb4cc5eb7 to your computer and use it in GitHub Desktop.
Save icameling/fc7e55c717e4a1db8079da9fb4cc5eb7 to your computer and use it in GitHub Desktop.
#链表 #链表相交
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* GetNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
// [head, cur node] 区间有 n 个node
ListNode* cur = dummy;
for (int i = 0; i < n; ++i) {
cur = cur->next;
}
// [candidate, cur] 区间有 n+1 个node
ListNode* candidate = dummy;
while (cur->next != NULL) {
cur = cur->next;
candidate = candidate->next;
}
// [ret node, last node] 区间有 n 个node
return candidate->next;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == NULL || headB == NULL)
return NULL;
int m = 0, n = 0;
ListNode* curA = headA;
while (curA != NULL) {
curA = curA->next;
m++;
}
ListNode* curB = headB;
while (curB != NULL) {
curB = curB->next;
n++;
}
bool is_A_shorter = m < n ? true : false;
int len_min = is_A_shorter ? m : n;
int len_max = is_A_shorter ? n : m;
ListNode* tmpShort = is_A_shorter ? headA : headB;
ListNode* headLong = is_A_shorter ? headB : headA;
ListNode* tmpLong = GetNthFromEnd(headLong, len_min);
while(tmpShort != NULL) {
if (tmpLong == tmpShort)
return tmpShort;
tmpShort = tmpShort->next;
tmpLong = tmpLong->next;
}
return NULL;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment