36、剑指offer--两链表的第一个公共结点

题目描述
输入两个链表,找出它们的第一个公共结点。
 
解题思路:本题先分别遍历两个链表一遍,求出两个链表的长度。并求出长度差值。然后让长度长的链表先走差值步,然后两个链表一起移动,直到两链表重合,返回第一个结点。
 
注意:判断条件while((pLong != NULL) && (pShort != NULL) && (pLong->val != pShort->val))
以上为正确的判断条件,while((pLong != NULL) && (pShort != NULL) && (pLong!= pShort)这样写在牛客网上能通过,但是在本地编译器,这样判断,只有当两个链表有一个为空时才会跳出循环,不是两链表重合就跳出循环。重合时pLong也不等于pShort
 1 /*
 2 struct ListNode {
 3     int val;
 4     struct ListNode *next;
 5     ListNode(int x) :
 6             val(x), next(NULL) {
 7     }
 8 };*/
 9 class Solution {
10 public:
11     ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
12         unsigned int length1 = GetListLength(pHead1);
13         unsigned int length2 = GetListLength(pHead2);
14  
15         int nLength = 0;
16         ListNode *pLong;
17         ListNode *pShort;
18         if(length1 > length2)
19         {
20             nLength = length1 - length2;
21             pLong = pHead1;
22             pShort = pHead2;
23         }
24         else
25         {
26             nLength = length2 - length1;
27             pLong = pHead2;
28             pShort = pHead1;
29         }
30  
31         for(int i=0;i<nLength;i++)
32         {
33             pLong = pLong->next;
34         }
35         //两链表已对齐
36         while((pLong != NULL) && (pShort != NULL) && (pLong->val != pShort->val))
37         {
38             pLong = pLong->next;
39             pShort = pShort->next;
40         }
41         ListNode *pFirstCommmonNode = pLong;
42         return pFirstCommmonNode;
43  
44     }
45     unsigned int GetListLength(ListNode *pHead)
46     {
47         unsigned int length = 0;
48         ListNode *pNode = pHead;
49         while(pNode != NULL)
50         {
51             length++;
52             pNode = pNode->next;
53         }
54         return length;
55     }
56 };
原文地址:https://www.cnblogs.com/qqky/p/6984638.html