/
Solution.java
executable file
·100 lines (76 loc) · 1.76 KB
/
Solution.java
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
93
94
95
96
97
98
99
100
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) return null;
ListNode curA = headA, curB = headB;
while(curA != null || curB != null){
if(curA == null) curA = headB;
if(curB == null) curB = headA;
if(curA == curB) return curA;
curA = curA.next;
curB = curB.next;
}
return null;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
int len(ListNode head){
int len = 0;
ListNode iter = head;
while(iter != null){
len++;
iter = iter.next;
}
return len;
}
ListNode trim(ListNode head, int count){
ListNode iter = head;
while(iter != null && count > 0){
count--;
iter = iter.next;
}
return iter;
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA = len(headA);
int lenB = len(headB);
int min = Math.min(lenA, lenB);
ListNode iterA = trim(headA, lenA - min);
ListNode iterB = trim(headB, lenB - min);
ListNode intersection = null;
while(iterA != null && iterB != null){
if(iterA.val != iterB.val){
intersection = null;
} else if (intersection == null){
intersection = iterA;
}
iterA = iterA.next;
iterB = iterB.next;
}
if (iterA != null || iterB != null){
return null;
}
return intersection;
}
}