Fork me on GitHub

找到两链表的第一个公共节点

【题目描述】

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

        For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

 
【解题思路】
    如果两个链表在某一个节点处汇合,那么其后的部分将成为二者的公共部分。

 

 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         if(pHead1==NULL||pHead2==NULL)
13             return NULL;
14         int listLen1=0;
15         int listLen2=0;
16         ListNode * pNode1=pHead1;
17         ListNode * pNode2=pHead2;
18         while(pNode1->next!=NULL)
19         {
20             pNode1=pNode1->next;
21             ++listLen1;
22         }
23         while(pNode2->next!=NULL)
24         {
25             pNode2=pNode2->next;
26             ++listLen2;
27         }
28 
29         if(pNode1!=pNode2)
30             return NULL;
31         else
32         {
33         int count=listLen1>listLen2?listLen1-listLen2:listLen2-listLen1;
34         if(listLen1>listLen2)
35         {
36             pNode1=pHead1;
37             pNode2=pHead2;
38         }
39         else
40         {
41             pNode1=pHead2;
42             pNode2=pHead1;
43         }
44 
45         while(count)
46         {
47             pNode1=pNode1->next;
48             --count;
49         }
50 
51         while(pNode1->next!=NULL&&pNode1!=pNode2)
52         {
53             pNode1=pNode1->next;
54             pNode2=pNode2->next;
55         }
56         return pNode1;
57         }    
58     }
59 };

 


Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.
【代码实现】
 
posted @ 2015-12-11 09:52  GeekerLou  阅读(536)  评论(0编辑  收藏  举报