-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0160-intersection-of-two-linked-lists.cpp
More file actions
92 lines (82 loc) · 1.73 KB
/
0160-intersection-of-two-linked-lists.cpp
File metadata and controls
92 lines (82 loc) · 1.73 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
/**
* Definition for singly-linked list.*/
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
bool flag1 = false, flag2 = false;
ListNode *a = headA;
ListNode *b = headB;
while (!flag1 || !flag2)
{
if (a == nullptr)
{
flag1 = true;
a = headB;
}
else
{
a = a->next;
}
if (b == nullptr)
{
flag2 = true;
b = headA;
}
else
{
b = b->next;
}
}
while (a != nullptr && b != nullptr) {
if (a == b) {
return a;
}
a = a -> next;
b = b -> next;
}
return nullptr;
}
};
void traverse(ListNode *l)
{
while (l != NULL)
{
cout << l->val;
l = l->next;
}
}
int main()
{
ListNode *a2 = new ListNode(1);
ListNode *a1 = new ListNode(4);
a1->next = a2;
ListNode *b3 = new ListNode(1);
ListNode *b2 = new ListNode(6);
ListNode *b1 = new ListNode(5);
b1 -> next = b2;
b2 -> next = b3;
ListNode *c3 = new ListNode(5);
ListNode *c2 = new ListNode(4);
ListNode *c1 = new ListNode(8);
c1 -> next = c2;
c2 -> next = c3;
a2 -> next = c1;
b3 -> next = c1;
ListNode *ans = (new Solution())->getIntersectionNode(a1, b1);
traverse(a1);
cout << endl;
traverse(b1);
cout << endl;
traverse(ans);
cout << endl;
}