-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersectionOfTwoLinkedList.java
More file actions
51 lines (42 loc) · 1.04 KB
/
intersectionOfTwoLinkedList.java
File metadata and controls
51 lines (42 loc) · 1.04 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 {
* 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;
}
int lenA = getLength(headA);
int lenB = getLength(headB);
while(lenA>lenB){
lenA--;
headA = headA.next;
}
while(lenB>lenA){
lenB--;
headB = headB.next;
}
while(headA!=headB){
headA = headA.next;
headB = headB.next;
}
return headA;
}
public static int getLength(ListNode head){
int count = 0;
ListNode temp = head;
while(temp!=null){
count += 1;
temp = temp.next;
}
return count;
}
}