File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Find Merge Point of Two Lists
3+
4+ Given pointers to the head nodes of linked lists that merge together at some point, find the Node where the two lists merge.
5+ It is guaranteed that the two head Nodes will be different, and neither will be NULL.
6+
7+ Find merge point of two linked lists
8+ head pointer input could be NULL as well for empty list
9+ Node is defined as
10+ class Node {
11+ int data;
12+ Node next;
13+ }
14+ */
15+
16+ public int mergePoint (Node headA , Node headB , int d ) {
17+
18+ for (int i =1 ;i <=d ;i ++)
19+ headA =headA .next ;
20+
21+ while (headA !=null && headB !=null )
22+ {
23+ if (headA .data ==headB .data )
24+ return headA .data ;
25+ headA =headA .next ;
26+ headB =headB .next ;
27+ }
28+
29+ return -1 ;
30+ }
31+
32+ int FindMergeNode (Node headA , Node headB ) {
33+
34+ int sum1 =0 ,sum2 =0 ,ans =-1 ;
35+
36+ Node temp = headA ;
37+
38+ while (temp !=null )
39+ {
40+ sum1 ++;
41+ temp =temp .next ;
42+ }
43+
44+ temp = headB ;
45+
46+ while (temp !=null )
47+ {
48+ sum2 ++;
49+ temp =temp .next ;
50+ }
51+
52+ int d = Math .abs (sum1 -sum2 );
53+
54+ if (sum1 >sum2 )
55+ ans = mergePoint (headA ,headB ,d );
56+ else
57+ ans = mergePoint (headB ,headA ,d );
58+
59+ return ans ;
60+
61+ }
You can’t perform that action at this time.
0 commit comments