剑指 Offer 52. 两个链表的第一个公共节点 LCOF
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int lenList(ListNode* head) {
int cnt = 0;
for(ListNode* p = head; p; p = p->next, cnt++);
return cnt;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lenA = lenList(headA), lenB = lenList(headB);
ListNode *p = headA, *q = headB;
for( ; lenA > lenB; p = p->next) lenA--;
for( ; lenA < lenB; q = q->next) lenB--;
while(p != q) {
p = p->next;
q = q->next;
}
return p;
}
};