java - Find Merge Point of Two Lists by reversing the Lists -
problem statement: you’re given pointer head nodes of 2 linked lists merge @ node. find node @ merger happens. 2 head nodes different , neither null.
input format have complete int findmergenode(node* heada, node* headb) method takes 2 arguments - heads of linked lists. should not read input stdin/console.
output format find node @ both lists merge , return data of node. not print stdout/console.
i trying reverse 2 lists , walk through each of them seperately until reach last common node. when tested, it's not giving correct ouput. thinking wrong or code wrong? approach or bad one?
my code:
int findmergenode(node heada, node headb) { //reverse lista node currenta = heada; node preva = null; node nexta; while(currenta!=null){ nexta = currenta.next; currenta.next = preva; preva = currenta; currenta = nexta; } heada = preva; //reverse listb node currentb = headb; node prevb = null; node nextb; while(currentb!=null){ nextb = currentb.next; currentb.next = prevb; prevb = currentb; currentb = nextb; } headb = prevb; //iterate throught reversed list , find last common node. node n = heada; node m = headb; while(n.next!=m.next){ n = n.next; m = m.next; } return n.data; }
link question: https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists
edit: karthik's answer, modified third while loop, still giving wrong output.
//iterate throught reversed list , find last common node. node n = heada; node m = headb; while(n.next == m.next){ n = n.next; m = m.next; } return n.data;
edit: should have been more clear explanation. because merge
if meant merging of values, reversing approach works. if meant merging of actual nodes, reversing approach not work because when reverse list merging point
can have next pointer.
a->b->c \ i->j->k / x->y
if list, when reverse cant have both c
, y
next pointer.because when reverse tree become
a<-b<-c i<-j<- k x <-y
but i
point either y
or c
depending on reversed later.
another easier approach(implementation wise) push nodes in 2 stack
s , once finish nodes start pop
ing elements , return last node same.
stack<node> stacka - push elements of lista stacka; stack<node> stackb - push elements of listb stacka; node result=null; while(stacka.peek() == stackb.peek()){ result = stacka.pop(); stackb.pop(); } return result;
below explanation answers original question
i did not check reversing list
logic, while loop after that(3rd while
loop) wrong :
while(n.next!=m.next){ n = n.next; m = m.next; }
the main point - should n.next == m.next
// ideally should check (n!=null && m!=null) // handles case there no common point while(n!=null && m!=null && n.next == m.next){ n = n.next; m = m.next; } return (n == null || m == null)? null : n;
because want find first node different , return previous node.
Comments
Post a Comment