-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
51 lines (49 loc) · 1.03 KB
/
Solution.cs
File metadata and controls
51 lines (49 loc) · 1.03 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
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution
{
public ListNode GetIntersectionNode(ListNode headA, ListNode headB)
{
int n1 = 0, n2 = 0;
ListNode dummy = headA;
while (dummy != null)
{
n1++;
dummy = dummy.next;
}
dummy = headB;
while (dummy != null)
{
n2++;
dummy = dummy.next;
}
int diff = n1 - n2;
if (diff > 0)
{
while (diff-- > 0)
{
headA = headA.next;
}
}
else
{
while (diff++ < 0)
{
headB = headB.next;
}
}
while (headA != null && headB != null)
{
if (headA == headB) return headA;
headA = headA.next;
headB = headB.next;
}
return null;
}
}