forked from dalanlan/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getIntersectionNode.cpp
69 lines (60 loc) · 1.07 KB
/
getIntersectionNode.cpp
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
//Intersection of two linked lists
/*
- If the two linked lists have no intersection at all, return null.
- The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
*/
/*
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
*/
int getCount(ListNode *head)
{
int count = 0;
ListNode *p = head;
while(p)
{
count++;
p = p->next;
}
return count;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
if(headA == NULL || headB == NULL)
return NULL;
int countA = getCount(headA);
int countB = getCount(headB);
int diff = abs(countA-countB);
ListNode *p,*q; // p: the bigger one; q: the smaller one
if(countA>countB)
{
p = headA;
q = headB;
}
else
{
p = headB;
q = headA;
}
while(diff != 0)
{
p = p->next;
diff--;
}
while(p && q)
{
if(p == q)
return p;
else
{
p = p ->next;
q = q ->next;
}
}
return NULL;
}