-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_161_IntersectionofTwoLinkedLists.java
More file actions
48 lines (46 loc) · 1.1 KB
/
simple_161_IntersectionofTwoLinkedLists.java
File metadata and controls
48 lines (46 loc) · 1.1 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
/**
* created by zl on 2019/3/28 10:50
*/
public class simple_161_IntersectionofTwoLinkedLists {
public ListNode getIntersectionNode(ListNode n1, ListNode n2)
{
if(n1==null || n2==null)
return null;
ListNode longlist= n1;
ListNode shortlist= n2;
int n1_len = 0;
int n2_len = 0;
while(n1.next!=null)
{
n1 = n1.next;
n1_len++;
}
while(n2.next!=null)
{
n2 = n2.next;
n2_len++;
}
//System.out.println(n1_len+","+n2_len);
int diff = n1_len>n2_len?(n1_len-n2_len):(n2_len-n1_len);
if(n1_len<n2_len)
{
ListNode tmp = shortlist;
shortlist = longlist;
longlist = tmp;
}
n1 = longlist;
n2 = shortlist;
while(diff>0)
{
n1 = n1.next;
diff--;
}
// System.out.println("n1.start="+n1.value);
while(n1!=null && n2!= null&&n1!=n2)
{
n1=n1.next;
n2=n2.next;
}
return n1;
}
}