C Puzzles

yet another place for C puzzles

Friday, March 19, 2010

 

one linked list meet another linked list

Linked List B meet Linked List A at node J. find J

linked list A. heada->x->....->J->......->z->null
linked list B headb->y->....->J

Comments:
something now in my mind..

use two stacks.
push nodes of linked list to the respective stack.

pop these stacks and compare.
initially we will get common nodes.
find the point where it is different.

complexity is O(n)
 
another solution without any major datastructure

length_a= get_length(heada);
length_b= get_length(headb);

delta = |length_a - length_b|;

if(length_a > length_b) {
step heada by delta
} else {
step headb by delta
}

now the length of both are same.

while(heada){
if (heada=headb)
print it
heada=heada->link;
headb=headb->link;
}
 
Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

July 2005   August 2005   October 2005   December 2005   March 2006   June 2006   July 2006   December 2006   February 2007   June 2007   March 2010   May 2010  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]