forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntersectionOfTwoLinkedLists.java
75 lines (65 loc) · 1.55 KB
/
IntersectionOfTwoLinkedLists.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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
// TC : O(l1 + l2)
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA = length(headA);
int lenB = length(headB);
if(lenA > lenB){
int diff = lenA -lenB;
while(diff>0){
headA = headA.next;
diff--;
}
} else{
int diff = lenB -lenA;
while(diff>0){
headB = headB.next;
diff--;
}
}
while(headA !=null && headB!=null){
if(headA == headB){
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
}
private int length(ListNode head){
int len = 0;
while(head!=null){
head = head.next;
len++;
}
return len;
}
// TC : O(l1+l2)
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA;
ListNode b = headB;
while(a!=b){
if(a == null){
a = headB;
} else{
a = a.next;
}
if(b == null){
b = headA;
} else{
b = b.next;
}
}
return a;
}
}