题目描述
输入两个链表,找出它们的第一个公共结点。
思路:先分别求出两个链表的长度m,n。长的那个链表先走m-n步(假设m>=n),然后同时走,碰到相同节点即为第一个公共节点,时间复杂度为O(m+n)
1 class Solution { 2 public: 3 int getLength(ListNode *pHead) 4 { 5 int count=0; 6 while(pHead) 7 { 8 ++count; 9 pHead=pHead->next; 10 } 11 return count; 12 } 13 ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { 14 if(pHead1==NULL || pHead2==NULL)return NULL; 15 int length1=getLength(pHead1); 16 int length2=getLength(pHead2); 17 while(length1>length2) 18 { 19 pHead1=pHead1->next; 20 --length1; 21 } 22 while(length2>length1) 23 { 24 pHead2=pHead2->next; 25 --length2; 26 } 27 while(pHead1 && pHead2) 28 { 29 if(pHead1==pHead2)return pHead1; 30 pHead1=pHead1->next; 31 pHead2=pHead2->next; 32 } 33 return NULL; 34 } 35 };