-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution160.cpp
More file actions
73 lines (60 loc) · 1.38 KB
/
solution160.cpp
File metadata and controls
73 lines (60 loc) · 1.38 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
/**
* Intersection of Two Linked Lists
*
* cpselvis([email protected])
* September 15th, 2016
*/
#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) {
ListNode *p = headA;
ListNode *q = headB;
bool flag1 = true;
bool flag2 = true;
while (headA != NULL && headB != NULL)
{
if (headA == headB)
{
return headA;
}
headA = headA -> next;
headB = headB -> next;
if (headA == NULL && flag1)
{
headA = q;
flag1 = false;
}
if (headB == NULL && flag2)
{
headB = p;
flag2 = false;
}
cout << "headA:" << headA -> val << endl;
cout << "headB:" << headB -> val << endl;
}
return NULL;
}
};
int main(int argc, char **argv)
{
ListNode *headA = new ListNode(1);
headA -> next = new ListNode(2);
ListNode *insec = new ListNode(3);
insec -> next = new ListNode(4);
insec -> next -> next = new ListNode(5);
ListNode *headB = new ListNode(6);
headB -> next = new ListNode(7);
headB -> next -> next = new ListNode(8);
headA -> next -> next = insec;
headB -> next -> next -> next = insec;
Solution s;
ListNode *intersection = s.getIntersectionNode(headA, headB);
cout << intersection -> val << endl;
}