-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode0160.java
More file actions
71 lines (64 loc) · 2.05 KB
/
Copy pathLeetCode0160.java
File metadata and controls
71 lines (64 loc) · 2.05 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
/* Intersection of Two Linked Lists
* Example:
* Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
* Output: Reference of the node with value = 8
* */
public class LeetCode0160 {
public static void main(String args[]){
int[] inputA = new int[]{4,1,8,4,5};
ListNode headA = buildListNode(inputA);
int[] inputB = new int[]{5,6,1};
ListNode headB = buildListNode(inputB);
headB.next.next.next = headA.next.next;
ListNode res = getIntersectionNode(headA, headB);
if(res != null)
System.out.println(res.val);
else
System.out.println(res);
}
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int countA = countList(headA);
int countB = countList(headB);
while(countA>countB){
headA = headA.next;
countA--;
}
while(countB>countA){
headB = headB.next;
countB--;
}
while(headA != null && headB !=null){
if(headA == headB)
return headA;
headA = headA.next;
headB = headB.next;
}
return null;
}
public static int countList(ListNode head){
int count = 0;
ListNode node = head;
while(node != null){
node = node.next;
count ++;
}
return count;
}
private static ListNode buildListNode(int[] input) {
ListNode first = null, last = null, newNode;
if (input.length > 0) {
for (int i = 0; i < input.length; i++) {
newNode = new ListNode(input[i]);
newNode.next = null;
if (first == null) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
last = newNode;
}
}
}
return first;
}
}