Skip to content

Commit 6f6894b

Browse files
committed
intersection_of_two_linked_lists
1 parent 45e24ae commit 6f6894b

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
139139
#### [153. find minimum in rotated sorted array](https://github.com/hitzzc/go-leetcode/tree/master/find_minimum_in_rotated_sorted_array)
140140
#### [154. find minimum in rotated sorted array II](https://github.com/hitzzc/go-leetcode/tree/master/find_minimum_in_rotated_sorted_array_II)
141141
#### [155. Min Stack](https://github.com/hitzzc/go-leetcode/tree/master/min_stack)
142+
#### [160. Intersection of Two Linked Lists](https://github.com/hitzzc/go-leetcode/tree/master/intersection_of_two_linked_lists)
142143

143144

144145

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
struct ListNode {
2+
int val;
3+
ListNode *next;
4+
ListNode(int x) : val(x), next(NULL) {}
5+
};
6+
7+
class Solution {
8+
public:
9+
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
10+
int count1 = 0;
11+
int count2 = 0;
12+
ListNode* p1 = headA;
13+
ListNode* p2 = headB;
14+
while (p1 != NULL) {
15+
++count1;
16+
p1 = p1->next;
17+
}
18+
while (p2 != NULL) {
19+
++count2;
20+
p2 = p2->next;
21+
}
22+
int diff;
23+
if (count1 > count2) {
24+
diff = count1 - count2;
25+
p1 = headA;
26+
p2 = headB;
27+
}else {
28+
diff = count2 - count1;
29+
p1 = headB;
30+
p2 = headA;
31+
}
32+
for (; diff > 0; --diff) p1 = p1->next;
33+
while (p1 != p2){
34+
p1 = p1->next;
35+
p2 = p2->next;
36+
}
37+
return p1;
38+
}
39+
};

0 commit comments

Comments
 (0)