-
-
Notifications
You must be signed in to change notification settings - Fork 422
/
intersection-of-two-linked-lists.java
63 lines (54 loc) · 1.45 KB
/
intersection-of-two-linked-lists.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
/**
* 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) {
int lenA = getLinkedListLength(headA);
int lenB = getLinkedListLength(headB);
ListNode head1 = headA;
ListNode head2 = headB;
if(lenA > lenB){
int diff = lenA - lenB;
head1 = moveList(diff, head1);
}
else{
int diff = lenB - lenA;
head2 = moveList(diff, head2);
}
while(head1 != null){
if(head1 == head2){
return head1;
}
else if(head1.next == head2.next){
return head1.next;
}
head1 = head1.next;
head2 = head2.next;
}
return null;
}
public int getLinkedListLength(ListNode head){
ListNode currentHead = head;
int len = 0;
while(currentHead != null){
currentHead = currentHead.next;
len++;
}
return len;
}
public ListNode moveList(int difference, ListNode head){
while(difference != 0){
head = head.next;
difference--;
}
return head;
}
}