-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersection-of-two-linked-lists(AC).cpp
More file actions
51 lines (45 loc) · 1.07 KB
/
Copy pathintersection-of-two-linked-lists(AC).cpp
File metadata and controls
51 lines (45 loc) · 1.07 KB
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
// 1AC, count the number of nodes and align them
/**
* 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) {
ListNode *p1, *p2;
int n1, n2;
p1 = headA;
n1 = 0;
while (p1 != nullptr) {
++n1;
p1 = p1->next;
}
p2 = headB;
n2 = 0;
while (p2 != nullptr) {
++n2;
p2 = p2->next;
}
p1 = headA;
p2 = headB;
int i;
if (n1 < n2) {
for (i = 0; i < n2 - n1; ++i) {
p2 = p2->next;
}
} else if (n1 > n2) {
for (i = 0; i < n1 - n2; ++i) {
p1 = p1->next;
}
}
while (p1 != nullptr && p2 != nullptr && p1 != p2) {
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
};