-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersectionOfTwoLists.java
More file actions
56 lines (51 loc) · 1.44 KB
/
Copy pathintersectionOfTwoLists.java
File metadata and controls
56 lines (51 loc) · 1.44 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
/**
* 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 lengthA = getLength(headA);
int lengthB = getLength(headB);
ListNode smallList;
ListNode tallList;
int tallLength;
int smallLength;
if(lengthA>lengthB){
smallList = headB;tallList=headA;
tallLength = lengthA; smallLength=lengthB;
}else{
smallList = headA;tallList=headB;
tallLength = lengthB; smallLength=lengthA;
}
while(tallLength>smallLength){
tallList = tallList.next;
tallLength = tallLength-1;
}
//starting from this point the lists are in the same level
while(tallList !=null){
if(tallList == smallList){
return smallList;
}
tallList = tallList.next;
smallList = smallList.next;
}
return null;
}
//get the length of a list
public int getLength(ListNode head){
ListNode iterator = head;
int index = 0;
while(iterator!=null){
index = index + 1;
iterator = iterator.next;
}
return index;
}
}