Skip to content

Commit ced1a26

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 5b8b656 commit ced1a26

File tree

2 files changed

+58
-10
lines changed

2 files changed

+58
-10
lines changed

0160_intersection_of_two_linked_list/intersection.c

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,27 @@ struct ListNode {
99

1010
static struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
1111
{
12+
if (headA == NULL || headB == NULL) {
13+
return NULL;
14+
}
15+
1216
struct ListNode *p;
1317
for (p = headA; p->next != NULL; p = p->next) {}
1418
p->next = headB;
1519

16-
bool first = true;
17-
struct ListNode *p0, *p1;
18-
for (p0 = headA, p1 = headA; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) {
19-
if (p0 == p1 && !first) {
20-
p0 = headA;
21-
while (p0 != p1) {
22-
p0 = p0->next;
23-
p1 = p1->next;
20+
struct ListNode *slow = headA, *fast = headA;
21+
while (fast != NULL && fast->next != NULL) {
22+
slow = slow->next;
23+
fast = fast->next->next;
24+
if (slow == fast) {
25+
slow = headA;
26+
while (slow != fast) {
27+
slow = slow->next;
28+
fast = fast->next;
2429
}
2530
p->next = NULL;
26-
return p0;
31+
return slow;
2732
}
28-
first = false;
2933
}
3034

3135
p->next = NULL;
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <stdc++.h>
2+
3+
using namespace std;
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* struct ListNode {
8+
* int val;
9+
* ListNode *next;
10+
* ListNode(int x) : val(x), next(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
16+
int lenA = getListLength(headA);
17+
int lenB = getListLength(headB);
18+
if (lenA > lenB) {
19+
for (int i = 0; i < lenA - lenB; i++) {
20+
headA = headA->next;
21+
}
22+
} else {
23+
for (int i = 0; i < lenB - lenA; i++) {
24+
headB = headB->next;
25+
}
26+
}
27+
28+
while (headA != nullptr && headB != nullptr && headA != headB) {
29+
headA = headA->next;
30+
headB = headB->next;
31+
}
32+
33+
return headA;
34+
}
35+
private:
36+
int getListLength(ListNode *h) {
37+
int len = 0;
38+
while (h != nullptr) {
39+
len++;
40+
h = h->next;
41+
}
42+
return len;
43+
}
44+
};

0 commit comments

Comments
 (0)