{"id":27322,"date":"2018-01-20T21:25:10","date_gmt":"2018-01-20T15:55:10","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27322"},"modified":"2018-01-20T21:25:10","modified_gmt":"2018-01-20T15:55:10","slug":"java-algorithm-write-program-function-detect-loop-linked-list","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-write-program-function-detect-loop-linked-list\/","title":{"rendered":"Java Algorithm &#8211; Write a program function to detect loop in a linked list"},"content":{"rendered":"<p>Given a linked list, check if the the linked list has loop or not. Below diagram shows a linked list with a loop.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-27343\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linked-List-Loop-1.png\" alt=\"C Algorithm - Write a program function to detect loop in a linked list\" width=\"300\" height=\"150\" \/><\/p>\n<p>Following are different ways of doing this<br \/>\n<strong>Use Hashing:<\/strong><br \/>\nTraverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false and if next of current node points to any of the previously stored nodes in Hash then return true.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Mark Visited Nodes:<\/strong><br \/>\nThis solution requires modifications to basic linked list data structure.\u00a0 Have a visited flag with each node.\u00a0 Traverse the linked list and keep marking visited nodes.\u00a0 If you see a visited node again then there is a loop. This solution works in O(n) but requires additional information with each node.<br \/>\nA variation of this solution that doesn\u2019t require modification to basic data structure can be implemented using hash.\u00a0 Just store the addresses of visited nodes in a hash and if you see an address that already exists in hash then there is a loop.<\/p>\n<p><strong>Floyd\u2019s Cycle-Finding Algorithm:<\/strong><br \/>\nThis is the fastest method. Traverse linked list using two pointers.\u00a0 Move one pointer by one and other pointer by two.\u00a0 If these pointers meet at some node then there is a loop.\u00a0 If pointers do not meet then linked list doesn\u2019t have loop.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Java Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to detect loop in a linked list<br\/>class LinkedList<br\/>{<br\/>    Node head;  \/\/ head of list<br\/>  <br\/>    \/* Linked list Node*\/<br\/>    class Node<br\/>    {<br\/>        int data;<br\/>        Node next;<br\/>        Node(int d) {data = d; next = null; }<br\/>    }<br\/>  <br\/>    \/* Inserts a new Node at front of the list. *\/<br\/>    public void push(int new_data)<br\/>    {<br\/>        \/* 1 &amp; 2: Allocate the Node &amp;<br\/>                  Put in the data*\/<br\/>        Node new_node = new Node(new_data);<br\/>  <br\/>        \/* 3. Make next of new Node as head *\/<br\/>        new_node.next = head;<br\/>  <br\/>        \/* 4. Move the head to point to new Node *\/<br\/>        head = new_node;<br\/>    }<br\/> <br\/>    int detectLoop()<br\/>    {<br\/>        Node slow_p = head, fast_p = head;<br\/>        while (slow_p != null &amp;&amp; fast_p != null &amp;&amp; fast_p.next != null) {<br\/>            slow_p = slow_p.next;<br\/>            fast_p = fast_p.next.next;<br\/>            if (slow_p == fast_p) {<br\/>                System.out.println(&quot;Found loop&quot;);<br\/>                return 1;<br\/>            }<br\/>        }<br\/>        return 0;<br\/>    }<br\/> <br\/>    \/* Drier program to test above functions *\/<br\/>    public static void main(String args[])<br\/>    {<br\/>        LinkedList llist = new LinkedList();<br\/> <br\/>        llist.push(20);<br\/>        llist.push(4);<br\/>        llist.push(15);<br\/>        llist.push(10);<br\/>         <br\/>        \/*Create loop for testing *\/<br\/>        llist.head.next.next.next.next = llist.head;<br\/> <br\/>        llist.detectLoop();<br\/>    }<br\/>} <br\/>\/* This code is contributed by Rajat Mishra. *\/<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Found loop<\/pre>\n<p><strong>Time Complexity:<\/strong> O(n)<br \/>\n<strong>Auxiliary Space:<\/strong> O(1)<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Algorithm &#8211; Write a program function to detect loop in a linked list &#8211; Linked List &#8211; Given a linked list, check if the the linked list has loop or not.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,2139,79476,79478],"tags":[76548,81431,81427,81429,81428,81430,81432,80598,81434,81433],"class_list":["post-27322","post","type-post","status-publish","format-standard","hentry","category-coding","category-java","category-linked-list","category-singly-linked-list","tag-cycle-detection-in-linked-list","tag-detect-cycle-in-linked-list-c","tag-detect-loop-in-linked-list-java","tag-find-merge-point-of-two-lists","tag-find-start-of-loop-in-linked-list","tag-floyds-cycle-finding-algorithm","tag-given-a-linked-list-return-the-node-where-the-cycle-begins-if-there-is-no-cycle-return-null","tag-how-to-find-3rd-element-from-end-in-a-linked-list-in-one-pass","tag-linked-list-cycle-ii","tag-remove-loop-in-linked-list"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27322","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27322"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27322\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27322"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27322"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27322"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}