Skip to main content

Finding a loop in a linked List

Finding a loop in a linked List:-

public class LinkedListLoop {

 //Two pointers
 public Node loopCheck(Node head)
 {
  //fast pointer take two steps at a time
  Node fastptr=head;
  //slow pointer take one step at a time
  Node slowptr=head;
  
  if(head==null)
  {
   System.out.println("no loops empty list");
  }
  
  //Till any pointer becomes null
  while(slowptr!=null && fastptr!=null && fastptr.next!=null)
  {
   slowptr=slowptr.next;
   fastptr=fastptr.next.next;
   
   //if both pointers point to same node
   //possible only in loop list
   if(slowptr==fastptr)
   {
    System.out.println("loopfound");
    fastptr=head;
    while(fastptr.next!=slowptr)
    {
     fastptr=fastptr.next;
    }
     return fastptr;
   }
  }
  System.out.println("loop not found");
   return head;
 }
 
 public void makeCycle(Node head)
 {
  Node temp=head;
  while(temp.next.next!=null)
  {
   temp=temp.next;
  }
  temp.next=head.next.next;
 }
 
 
}

Comments

.

Popular posts from this blog

Adding Node at the End of Linked List

Adding Node at the End of Linked List:- The method takes two parameter one a head node of a linked list and other data too insert. public void addNodeEnd ( Node head , int data ) { if ( head == null ) { System . out . println ( "list is empty" ); return ; } Node node = new Node ( data ); Node temp = head ; while ( temp . next != null ) { temp = temp . next ; } temp . next = node ; } To Know the basic structure of the linked list click here

DEPTH FIRST SEARCH IN JAVA

DEPTH FIRST SEARCH IN JAVA public void dfs () { vertex [ 0 ]. visited = true ; displyVertex ( 0 ); stackobj . push ( 0 ); while (! stackobj . isEmpty ()) { int v = adjVertex (( Integer ) stackobj . peek ()); if ( v ==- 1 ) { stackobj . pop (); } else { vertex [ v ]. visited = true ; displyVertex ( v ); stackobj . push ( v ); } } }