Skip to content

Commit f54c73f

Browse files
Accepted
1 parent 9d04e51 commit f54c73f

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/**
2+
* Created by gouthamvidyapradhan on 24/03/2017.
3+
* Accepted
4+
*/
5+
public class IntersectionOfLinkedList
6+
{
7+
static class ListNode
8+
{
9+
int val;
10+
ListNode next;
11+
ListNode(int x)
12+
{
13+
val = x;
14+
next = null;
15+
}
16+
}
17+
18+
/**
19+
* Main method
20+
* @param args
21+
*/
22+
public static void main(String[] args) throws Exception
23+
{
24+
ListNode one1 = new ListNode(1);
25+
ListNode one2 = new ListNode(2);
26+
ListNode one3 = new ListNode(3);
27+
ListNode one4 = new ListNode(4);
28+
ListNode one5 = new ListNode(5);
29+
one1.next = one2;
30+
one2.next = one3;
31+
one3.next = one4;
32+
one4.next = one5;
33+
34+
ListNode two1 = new ListNode(1);
35+
ListNode two2 = new ListNode(2);
36+
ListNode two3 = new ListNode(3);
37+
two1.next = two2;
38+
two2.next = two3;
39+
two3.next = one5;
40+
ListNode node = new IntersectionOfLinkedList().getIntersectionNode(one1, two1);
41+
System.out.println(node.val);
42+
}
43+
44+
public ListNode getIntersectionNode(ListNode headA, ListNode headB)
45+
{
46+
ListNode first = headA;
47+
ListNode second = headB;
48+
int countA = 0, countB = 0;
49+
while(first != null)
50+
{
51+
first = first.next;
52+
countA++;
53+
}
54+
while(second != null)
55+
{
56+
second = second.next;
57+
countB++;
58+
}
59+
first = headA;
60+
second = headB;
61+
if(countA > countB)
62+
{
63+
int diff = countA - countB;
64+
countA = 0;
65+
while(countA < diff)
66+
{
67+
first = first.next;
68+
countA++;
69+
}
70+
71+
}
72+
else if(countB > countA)
73+
{
74+
int diff = countB - countA;
75+
countB = 0;
76+
while(countB < diff)
77+
{
78+
second = second.next;
79+
countB++;
80+
}
81+
}
82+
ListNode join = null;
83+
while(first != null && second != null && !first.equals(second))
84+
{
85+
first = first.next;
86+
second = second.next;
87+
}
88+
if(first != null && second != null && first.equals(second))
89+
join = first;
90+
return join;
91+
}
92+
93+
}

0 commit comments

Comments
 (0)