Find if a singly linked List has loop or not. How to find out middle element from a looped single linked list

View previous topic View next topic Go down

Find if a singly linked List has loop or not. How to find out middle element from a looped single linked list

Post  Admin on Wed Aug 24, 2011 6:08 pm

public boolean findloop(LinkedListNode head){
LinkedListNode n1=head;
LinkedListNode n2=head;
n1=n1.next;
n2=n2.next.next;
while(n2!=null){
if(n1==n2)
break;
n1=n1.next;
n2=n2.next.next;
}
if(n2==null)
return false;
return true;
}

Admin
Admin

Posts : 131
Join date : 2011-08-16

View user profile http://codefornongeek.forumotion.com

Back to top Go down

Re: Find if a singly linked List has loop or not. How to find out middle element from a looped single linked list

Post  viterbi on Thu Sep 08, 2011 10:07 pm

The program will fail in multiple situations, for example, what if linked list had odd number of nodes? What if it has only one nodes? I have found out that the interviewers are always very concerned about these corner cases. I often forgot to address it, it's better we begin to pay attention now.

viterbi

Posts : 32
Join date : 2011-09-03

View user profile

Back to top Go down

Re: Find if a singly linked List has loop or not. How to find out middle element from a looped single linked list

Post  skyboard on Mon Oct 03, 2011 4:24 pm

ListNode FindBeginning(ListNode head){
ListNode n1=head;
ListNode n2=head;
//Find meeting point
while(n2.next!=null){
n1=n1.next;
n2=n2.next.next;
if(n1==n2){
break;
}
}
if(n2.next==null)
return null;
n1=head;
while(n1!=n2){
n1=n1.next;
n2=n2.next;
}
return n2;
}

skyboard

Posts : 31
Join date : 2011-09-03

View user profile

Back to top Go down

Re: Find if a singly linked List has loop or not. How to find out middle element from a looped single linked list

Post  Sponsored content


Sponsored content


Back to top Go down

View previous topic View next topic Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum