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;
   System.out.println("no loops empty list");
  //Till any pointer becomes null
  while(slowptr!=null && fastptr!=null &&!=null)
   //if both pointers point to same node
   //possible only in loop list
     return fastptr;
  System.out.println("loop not found");
   return head;
 public void makeCycle(Node head)
  Node temp=head;



Popular posts from this blog

Deleting a Node by passing data in LInkedList

Deleting a Node by passing data in LInkedList:-

The node can be deleted by passing the data value in a function.Here we have three pointers one to traverse the list other to point current node and third one to point previous of current node.

//deleting a given keypublic Node deleteKeyNode(Node head,int key){//traverse pointer Node temp=head;//previous pointer Node prevtemp=temp;while(temp!=null){//when key is at head positionif({; System.out.println("head is deleted");return head;}//when key is at any position other than headif({;; temp=prevtemp;} prevtemp=temp;;}return head;}