输入两个链表,找出它们的第一个公共结点。
C++
/*
struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}
};*/
class Solution {
public:int get_len(ListNode* root){int res=0;ListNode* p=root;while(p){res++;p=p->next;}return res;}ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {int len1=get_len(pHead1);int len2=get_len(pHead2);ListNode* root1=NULL;ListNode* root2=NULL;if(len1>len2){root1=pHead1;root2=pHead2;}else{root1=pHead2;root2=pHead1;}int num=abs(len1-len2);while(num){root1=root1->next;num--;}ListNode* p=NULL;while(root1){if(root1->val==root2->val){p=root1;break;}else{root1=root1->next;root2=root2->next;}}return p;}
};