-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersectionOfTwoLinkedLists.java
More file actions
104 lines (82 loc) · 2.27 KB
/
Copy pathintersectionOfTwoLinkedLists.java
File metadata and controls
104 lines (82 loc) · 2.27 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package LeetCode;
/**
* Definition for singly-linked list. public class ListNode { int val; ListNode
* next; ListNode(int x) { val = x; next = null; } }
*/
public class intersectionOfTwoLinkedLists {
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA = 0, lenB = 0 , diff;
ListNode startA = headA;
ListNode startB = headB ;
while (headA != null) {
// System.out.print(headA.val + " ");
lenA++;
headA = headA.next;
}
while (headB != null) {
// System.out.print(headB.val + " ");
lenB++;
headB = headB.next;
}
if(lenA == 1 && lenB ==1 && startA.val == startB.val){
return startA;
}
/* if(lenA == 0 || lenA==1 || lenB == 0 || lenB==1)
return null;*/
diff = Math.abs(lenA-lenB) ;
//balancing
if(diff > 0){
if(lenA > lenB){
while(diff>0){
startA = startA.next;
diff--;
}
}
else{
while(diff>0){
startB = startB.next;
diff--;
}
}
}
//After balancing is done or case when balancing not required
while(startA != null && startB != null){
if(startA == startB){
return startA;
}
startA = startA.next;
startB = startB.next;
}
return null;
}
public static void main(String[] args) {
ListNode firstA = new ListNode(1);
ListNode secondA = new ListNode(2);
ListNode third = new ListNode(3);
ListNode fourth = new ListNode(4);
ListNode fifth = new ListNode(5);
ListNode sixth = new ListNode(6);
firstA.next = secondA;
firstA.next.next = third;
firstA.next.next.next = fourth;
firstA.next.next.next.next = fifth;
firstA.next.next.next.next.next = sixth;
ListNode firstB = new ListNode(7);
ListNode secondB = new ListNode(8);
ListNode thirdB = new ListNode(9);
firstB.next = secondB;
firstB.next.next = thirdB;
firstB.next.next.next = third;
ListNode res = getIntersectionNode(firstA, firstB);
if(res == null)
System.out.println("No Intersection");
else
System.out.println(res.val);
}
}
/*
* while(headA!=null){ System.out.print(headA.val + " "); headA = headA.next; }
* System.out.println("\n");
*
* while(headB!=null){ System.out.print(headB.val + " "); headB = headB.next; }
*/