题目描述
输入两个链表,找出它们的第一个公共结点。
代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode *q1=pHead1,*q2=pHead2;
if(!pHead1) return nullptr;
if(!pHead2) return nullptr;
while(q1!=q2){
q1=q1->next;
q2=q2->next;
if(q1==nullptr&&q2!=nullptr) q1=pHead2;
if(q2==nullptr&&q1!=nullptr) q2=pHead1;
if(!q1&&!q2)
return nullptr;
}
return q1;
}
};