[剑指Offer] 36.两个链表的第一个公共结点

题目描述

输入两个链表,找出它们的第一个公共结点。

【思路】找出两个链表的长度,然后让长的走两个链表的长度差,然后再一起走(因为两个链表用公共的尾部)。

 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 {
11 public:
12     int Find_Length(ListNode* p){
13         int len = 0;
14         while(p){
15             len ++;
16             p = p->next;
17         }
18         return len;
19     }
20     void Walk_Step(ListNode* &p,int x){
21         while(x--){
22             p = p->next;
23         }
24     }
25     ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2)
26     {
27         int len1 = Find_Length(pHead1);
28         int len2 = Find_Length(pHead2);
29         int x = abs(len1 - len2);
30         if(len1 < len2) 
31             Walk_Step(pHead2,x);
32         else
33             Walk_Step(pHead1,x);
34         while(pHead1 != pHead2){
35             pHead1 = pHead1->next;
36             pHead2 = pHead2->next;
37         }
38         return pHead1;
39     }
40 };

 

posted @ 2017-03-07 16:56  Strawberry丶  阅读(137)  评论(0编辑  收藏  举报