/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ int hascommonnode(struct ListNode *phead1,struct ListNode*phead2,int* x1,int *x2) { struct ListNode *tail1=phead1,*tail2=phead2; while(tail1->next!=NULL) { tail1=tail1->next; (*x1)++; } while(tail2->next!=NULL) { tail2=tail2->next; (*x2)++; } if(tail1==tail2) { return true; } else { return false; } } struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) { // write code here int x1=0,x2=0; if(pHead1==NULL||pHead2==NULL) return NULL; int p=hascommonnode(pHead1,pHead2,&x1,&x2); if(p==0) { return NULL; } struct ListNode *fastpointer= x1>x2 ? pHead1:pHead2,*slowpointer; if(fastpointer==pHead1) { slowpointer=pHead2; } else { slowpointer=pHead1; } int num=abs(x1-x2); while(num>0) { fastpointer=fastpointer->next; num--; } while(fastpointer!=slowpointer) { fastpointer=fastpointer->next; slowpointer=slowpointer->next; } return fastpointer; }