Code For NonGeek
Would you like to react to this message? Create an account in a few clicks or log in to continue.

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

3 posters

Go down

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

Post  Admin 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

https://codefornongeek.forumotion.com

Back to top Go down

Find if a singly linked List has loop or not. How to find out middle element from a looped single linked list Empty 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 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

Back to top Go down

Find if a singly linked List has loop or not. How to find out middle element from a looped single linked list Empty 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 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

Back to top Go down

Find if a singly linked List has loop or not. How to find out middle element from a looped single linked list Empty 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

Back to top

- Similar topics

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