让指针走完两条链表,并且最多只能走一次。如果任何一个链表为空则直接返回空指针。
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { if(!pHead1 || !pHead2) return NULL; ListNode* p = pHead1; ListNode* q = pHead2; int cnt1 = 0; int cnt2 = 0; while((p != q) && cnt1 <= 1 && cnt2 <= 1) { if(p == NULL) { p = pHead2; cnt1++; } if(q == NULL) { q = pHead1; cnt2++; } if(p==q) break; p = p->next; q = q->next; } return p; } };