剑指offer52. 两个链表第一个公共节点 P253
题目:输入两个链表,找出它们的第一个公共结点。
统计两个链表的长度差sub,长的先走sub步,第二次遍历看两个工作指针是不是相等
int getLength(ListNode *head) { // 统计链表长度
if (head == NULL) return 0;
int count = 0;
ListNode *p = head;
while (p != NULL) {
p = p -> m_pNext;
++count;
}
return count;
}
// 找两个链表长度差值sub,长的先走sub步,然后一起出发看指针是否相同即可
ListNode* FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2){
int len1 = getLength(pHead1);
int len2 = getLength(pHead2);
if (len1 == 0 || len2 == 0) return NULL;
ListNode *p, *q;
int sub = len1 > len2 ? (len1 - len2) : (len2 - len1);
if (len1 > len2) {
p = pHead1;
q = pHead2;
} else {
p = pHead2;
q = pHead1;
}
while (sub--) p = p ->m_pNext;
while (p != q && p != NULL && q != NULL) {
p = p -> m_pNext;
q = q -> m_pNext;
}
if (p == NULL || q == NULL) return NULL; // 没有公共节点
else return p;
}