You are viewing a single comment's thread. Return to all comments →
OPTIMIZED APPROACH
static int length(SinglyLinkedListNode temp) { int len =0; while(temp != null) { len++; temp = temp.next; } return len; } static int findMergeNode(SinglyLinkedListNode head1, SinglyLinkedListNode head2) { int len1 = length(head1); int len2 = length(head2); int mov = 0; SinglyLinkedListNode temp = null; boolean head1_moved = false; boolean head2_moved = false; if(len1 > len2) { mov = len1 - len2; temp = head1; while(mov-- > 0) { temp = temp.next; } head1_moved = true; } else if(len1 <= len2) { mov = len2 - len1; temp = head2; while(mov-- > 0) { temp = temp.next; } head2_moved = true; } if(head1_moved) { SinglyLinkedListNode curr = head2; while(temp != null) { if(curr == temp) { return curr.data; } temp = temp.next; curr = curr.next; } } else if(head2_moved){ SinglyLinkedListNode curr = head1; while(temp != null) { if(curr == temp) { return curr.data; } temp = temp.next; curr = curr.next; } } return -1; }
Seems like cookies are disabled on this browser, please enable them to open this website
Find Merge Point of Two Lists
You are viewing a single comment's thread. Return to all comments →
OPTIMIZED APPROACH