【Leetcode】160. Intersection of Two Linked Lists

160. Intersection of Two Linked Lists

【题目】中文版   英文版

 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 {
13         int a = 0, b = 0;
14         ListNode *tempA = headA, *tempB = headB;
15         
16         while(tempA) 
17         {
18             a++;
19             tempA = tempA->next;
20         }
21         
22         while(tempB) 
23         {
24             b++;
25             tempB = tempB->next;
26         }
27         
28         tempA = headA;
29         tempB = headB;
30         
31         int difference = a - b;
32        
33         while(difference > 0) 
34         {
35             tempA = tempA->next;
36             difference--;
37         }
38         
39         while(difference < 0) 
40         {
41             tempB = tempB->next;
42             difference++;
43         }
44         
45         while(tempA != tempB) 
46         {
47             tempA = tempA->next;
48             tempB = tempB->next;
49         }
50         
51         return tempA;
52     }
53 };

猜你喜欢

转载自www.cnblogs.com/sunbines/p/9147591.html
今日推荐