160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

 

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  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
12         if(!headA){
13             return NULL;
14         }else if(!headB){
15             return NULL;
16         }
17         ListNode* ListLong = headA;
18         ListNode* ListShort = headB;
19         
20         int length1 = GetListLength(headA);
21         int length2 = GetListLength(headB);
22         int diffLength = length1 - length2;
23         
24         if(length2 > length1){
25             ListLong = headB;
26             ListShort = headA;
27             diffLength = length2 - length1;
28         }
29         
30         for(int i = 0 ; i < diffLength; i++){
31             ListLong = ListLong->next;
32         }
33         
34         while((ListLong != NULL) && (ListShort != NULL) && (ListLong != ListShort)){
35             ListLong = ListLong->next;
36             ListShort = ListShort->next;
37         }
38         
39         ListNode* CommonNode = ListLong;
40         return CommonNode;
41         
42     }
43     unsigned int GetListLength(ListNode* pHead){
44         unsigned int length = 0;
45         ListNode* pNode = pHead;
46         while(pNode != NULL){
47             ++length;
48             pNode = pNode->next;
49         }
50         return length;
51     }
52 };

 

posted on 2016-09-12 20:32  三颗心  阅读(171)  评论(0编辑  收藏  举报

导航