-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersection_of_linked_lists.cpp
More file actions
107 lines (93 loc) · 2.06 KB
/
intersection_of_linked_lists.cpp
File metadata and controls
107 lines (93 loc) · 2.06 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* =====================================================================================
*
* Filename: intersection_of_linked_lists.cpp
*
* Description: 160. Intersection of Two Linked Lists. Write a program to find the
* node at which the intersection of two singly linked lists begins.
*
* Version: 1.0
* Created: 02/25/19 03:50:57
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution1
{
public:
ListNode* getIntersectionNode(ListNode* a, ListNode* b)
{
int m = 0;
int n = 0;
auto* p = a;
while (p != NULL)
{
m++;
p = p->next;
}
p = b;
while (p != NULL)
{
n++;
p = p->next;
}
while (m > n)
{
a = a->next;
m--;
}
while (n > m)
{
b = b->next;
n--;
}
while (a != b)
{
a = a->next;
b = b->next;
}
return a;
}
};
// Two pointers
class Solution2
{
public:
ListNode* getIntersectionNode(ListNode* a, ListNode* b)
{
if (a == NULL || b == NULL)
{
return NULL;
}
ListNode* p = a;
ListNode* q = b;
// If two lists intersect, p and q will meet in the next iteration.
// Otherwise, p and q will both equal NULL pointer.
while (p != q)
{
p = (p != NULL ? p->next : b);
q = (q != NULL ? q->next : a);
}
return p;
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
ListNode* a = NULL;
ListNode* b = NULL;
auto* node = Solution().getIntersectionNode(a, b);
return 0;
}