-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntersectionOfTwoLinkedList.cpp
75 lines (63 loc) · 1.49 KB
/
IntersectionOfTwoLinkedList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* @file IntersectionOfTwoLinkedList.cpp
* @brief
* @author nhzc [email protected]
* @version 1.0.0
* @date 2014-11-30
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr){
return nullptr;
}
int lengthA = 0;
int lengthB = 0;
ListNode *next = headA;
ListNode *preA = headA;
while ( next != nullptr){
preA = next;
next = next -> next;
lengthA ++;
}
next = headB;
ListNode *preB = headB;
while ( next != nullptr){
preB = next;
next = next -> next;
lengthB ++;
}
if (preB != preA){
return nullptr;
}
preB = headB;
preA = headA;
if (lengthA > lengthB){
int count = lengthA - lengthB;
while (count != 0){
preA = preA -> next;
count --;
}
}
else{
int count = lengthB - lengthA;
while (count != 0){
preB = preB -> next;
count --;
}
}
while (preA != preB){
preA = preA -> next;
preB = preB -> next;
}
return preA;
}
};