Algorithms

How to Detect loop in a linked list

<p>In this article&comma; we will discuss an algorithm on how to detect a loop in a linked list&period; So&comma; in a given linked list&comma; check whether it contains the loop in it&comma; if yes then find the Loop length&period; As know that&comma; a singly linked list has several nodes&comma; and each node in the list has the content and a pointer to the next node in the list&period; It does not store any pointer to the previous node&period;<&sol;p>&NewLine;<h2>Algorithms related to the Singly Linked list<&sol;h2>&NewLine;<p>There are the following algorithms&comma; we have discussed related to the singly linked list<&sol;p>&NewLine;<blockquote>&NewLine;<ul>&NewLine;<li><strong><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;nth-node-from-the-end-of-a-singly-linked-list&sol;">Find the nth node from the end of a singly linked list<&sol;a><&sol;strong><&sol;li>&NewLine;<li><strong><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;find-the-middle-element-in-a-linked-list&sol;">Find the middle element in a linked list<&sol;a><&sol;strong><&sol;li>&NewLine;<li><strong><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;reverse-linked-list&sol;">How to Reverse linked list in Java<&sol;a><&sol;strong><&sol;li>&NewLine;<li><strong><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;delete-given-node-from-singly-linked-list&sol;">Delete given node from a singly linked list<&sol;a><&sol;strong><&sol;li>&NewLine;<li><strong><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;remove-duplicates-from-the-unsorted-singly-linked-list&sol;">Remove Duplicates from the Unsorted Singly Linked list<&sol;a><&sol;strong><&sol;li>&NewLine;<&sol;ul>&NewLine;<&sol;blockquote>&NewLine;<h2>Detect loop in a linked list<&sol;h2>&NewLine;<p>Let&&num;8217&semi;s see the following diagram of the singly linked list&colon;<br &sol;>&NewLine;<img class&equals;"aligncenter wp-image-4278 size-full" src&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-content&sol;uploads&sol;2018&sol;09&sol;Linked-List-Loop&period;png" alt&equals;"Detect loop in a linked list" width&equals;"583" height&equals;"228" &sol;><&sol;p>&NewLine;<p>As you can see in the above diagram&comma; loop in a linked list means the last node does not point to the null&comma; instead it points to some node in the list&period; There are are several approaches to solve this problem&period;<&sol;p>&NewLine;<h3>Approach 1&colon; Using Hashing<&sol;h3>&NewLine;<p>Navigate the linked list and put each node to the HashSet if the node is not present in the HashSet if node is present in the HashSet that means the given singly linked list has a loop&period;<&sol;p>&NewLine;<h3>Approach 2&colon; Using Fast and Slow pointers<&sol;h3>&NewLine;<p>This is a very efficient approach to detect a loop in a linked list&period;<&sol;p>&NewLine;<p><strong>Step 1&colon;<&sol;strong> Let&&num;8217&semi;s take two pointers slow and fast&period;<br &sol;>&NewLine;<strong>Step 2&colon;<&sol;strong> Intialize both pointers slow &equals; head and fast &equals; head&period;next&period;next&period;<br &sol;>&NewLine;<strong>Step 3&colon;<&sol;strong> Navigate both pointers&comma; slow pointer moves one node at a time but fast pointer moves two nodes a time&period;<br &sol;>&NewLine;<strong>Step 4&colon;<&sol;strong> If both pointers meet at some point&comma; we have found the loop&period;<br &sol;>&NewLine;<strong>Step 5&colon;<&sol;strong> Now find the loop length<br &sol;>&NewLine;<strong>Step 6&colon;<&sol;strong> At the point where both pointers have met&comma; stop one pointer and keep moving the another one<br &sol;>&NewLine;<strong>Step 7&colon;<&sol;strong> When another pointer meets the first pointer&comma; stop&period;<br &sol;>&NewLine;<strong>Step 8&colon;<&sol;strong> Keep counting number of hops&comma; that will your loop length<&sol;p>&NewLine;<p>Let&&num;8217&semi;s see the complete code for this algorithm&period;<&sol;p>&NewLine;<pre>package com&period;dineshonjava&period;algo&period;linkedlist&semi; &NewLine; &NewLine;&sol;&ast;&ast; &NewLine; &ast; &commat;author Dinesh&period;Rajput &NewLine; &ast; &NewLine; &ast;&sol; &NewLine;public class Node &lbrace; &NewLine;&Tab; &NewLine; Node next&semi; &NewLine; String data&semi; &NewLine; &NewLine; public Node&lpar;String data&rpar; &lbrace; &NewLine;&Tab;super&lpar;&rpar;&semi; &NewLine;&Tab;this&period;data &equals; data&semi; &NewLine; &rcub; &NewLine;&rcub; &NewLine; &NewLine;<&sol;pre>&NewLine;<p>Code for loop detection in the linked list<br &sol;>&NewLine;<strong>LoopInLinkedList&period;java<&sol;strong><&sol;p>&NewLine;<pre>&sol;&ast;&ast; &NewLine; &ast; &NewLine; &ast;&sol; &NewLine;package com&period;dineshonjava&period;algo&period;linkedlist&semi; &NewLine; &NewLine;&sol;&ast;&ast; &NewLine; &ast; &commat;author Dinesh&period;Rajput &NewLine; &ast; &NewLine; &ast;&sol; &NewLine;public class LoopInLinkedList &lbrace; &NewLine;&Tab; &NewLine;&Tab;public static void main&lpar;String&lbrack;&rsqb; args&rpar; &lbrace; &NewLine;&Tab;&Tab;Node head &equals; new Node&lpar;"1"&rpar;&semi; &NewLine;&Tab;&Tab;head&period;next &equals; new Node&lpar;"2"&rpar;&semi; &NewLine;&Tab;&Tab;head&period;next&period;next &equals; new Node&lpar;"3"&rpar;&semi; &NewLine;&Tab;&Tab;head&period;next&period;next&period;next &equals; new Node&lpar;"4"&rpar;&semi; &NewLine;&Tab;&Tab;head&period;next&period;next&period;next&period;next &equals; new Node&lpar;"5"&rpar;&semi; &NewLine;&Tab;&Tab;head&period;next&period;next&period;next&period;next&period;next &equals; new Node&lpar;"6"&rpar;&semi; &NewLine;&Tab;&Tab;head&period;next&period;next&period;next&period;next&period;next&period;next &equals; new Node&lpar;"7"&rpar;&semi; &NewLine;&Tab;&Tab;head&period;next&period;next&period;next&period;next&period;next&period;next&period;next &equals; head&period;next&period;next&semi; &NewLine;&Tab;&Tab;findLoop&lpar;head&rpar;&semi; &NewLine;&Tab;&rcub; &NewLine;&Tab; &NewLine;&Tab;private static void findLoop&lpar;Node head&rpar; &lbrace; &NewLine;&Tab;&Tab;Node slow &equals; head&semi; &NewLine;&Tab;&Tab;Node fast &equals; head&period;next&period;next&semi; &NewLine;&Tab;&Tab;while&lpar;slow &excl;&equals; null&rpar; &lbrace; &NewLine;&Tab;&Tab;&Tab;if&lpar;slow &equals;&equals; fast&rpar; &lbrace; &NewLine;&Tab;&Tab;&Tab;&Tab;System&period;out&period;println&lpar;"Loop Found in Linked List"&rpar;&semi; &NewLine;&Tab;&Tab;&Tab;&Tab;int lengthLoop &equals; findLength&lpar;slow&comma; fast&rpar;&semi; &NewLine;&Tab;&Tab;&Tab;&Tab;break&semi; &NewLine;&Tab;&Tab;&Tab;&rcub;else &lbrace; &NewLine;&Tab;&Tab;&Tab;&Tab;slow &equals; slow&period;next&semi; &NewLine;&Tab;&Tab;&Tab;&Tab;fast &equals; fast&period;next&period;next&semi; &NewLine;&Tab;&Tab;&Tab;&rcub; &NewLine;&Tab;&Tab;&rcub; &NewLine;&Tab;&rcub; &NewLine; &NewLine;&Tab;private static int findLength&lpar;Node firstPtr&comma; Node secondPtr&rpar; &lbrace; &NewLine;&Tab;&Tab;secondPtr &equals; secondPtr&period;next&semi; &NewLine;&Tab;&Tab;int lengthLoop &equals; 1&semi; &NewLine;&Tab;&Tab;while&lpar;secondPtr &excl;&equals; firstPtr&rpar; &lbrace; &NewLine;&Tab;&Tab;&Tab;lengthLoop&plus;&plus;&semi; &NewLine;&Tab;&Tab;&Tab;secondPtr &equals; secondPtr&period;next&semi; &NewLine;&Tab;&Tab;&rcub; &NewLine;&Tab;&Tab;System&period;out&period;println&lpar;"Length of Loop is "&plus;lengthLoop&rpar;&semi; &NewLine;&Tab;&Tab;return lengthLoop&semi; &NewLine;&Tab;&rcub; &NewLine; &NewLine;&rcub; &NewLine; &NewLine;<&sol;pre>&NewLine;<p>Run above program&comma; you will get the following <strong>output<&sol;strong>&colon;<&sol;p>&NewLine;<pre>Loop Found in Linked List &NewLine;Length of Loop is 5 &NewLine;<&sol;pre>&NewLine;<p>In this example&comma; we have written a program to detect a loop in a linked list<&sol;p>&NewLine;<p>Hope&comma; you have understood this solution&period; Please share other solutions if you have&period; &colon;&rpar;&period;<&sol;p>&NewLine;<p>Happy learning with us&excl;&excl;&excl;&period;<&sol;p>&NewLine;<div align&equals;"center"><iframe style&equals;"width&colon; 120px&semi; height&colon; 240px&semi;" src&equals;"&sol;&sol;ws-in&period;amazon-adsystem&period;com&sol;widgets&sol;q&quest;ServiceVersion&equals;20070822&amp&semi;OneJS&equals;1&amp&semi;Operation&equals;GetAdHtml&amp&semi;MarketPlace&equals;IN&amp&semi;source&equals;ac&amp&semi;ref&equals;tf&lowbar;til&amp&semi;ad&lowbar;type&equals;product&lowbar;link&amp&semi;tracking&lowbar;id&equals;dineshonjav06-21&amp&semi;marketplace&equals;amazon&amp&semi;region&equals;IN&amp&semi;placement&equals;1787127567&amp&semi;asins&equals;1787127567&amp&semi;linkId&equals;a1e64f621b5e6128d8cb10e876eb1c48&amp&semi;show&lowbar;border&equals;true&amp&semi;link&lowbar;opens&lowbar;in&lowbar;new&lowbar;window&equals;true&amp&semi;price&lowbar;color&equals;333333&amp&semi;title&lowbar;color&equals;0066c0&amp&semi;bg&lowbar;color&equals;ffffff" frameborder&equals;"0" marginwidth&equals;"0" marginheight&equals;"0" scrolling&equals;"no" align&equals;"center"><span data-mce-type&equals;"bookmark" style&equals;"display&colon; inline-block&semi; width&colon; 0px&semi; overflow&colon; hidden&semi; line-height&colon; 0&semi;" class&equals;"mce&lowbar;SELRES&lowbar;start"><&sol;span><br &sol;>&NewLine;<&sol;iframe><&sol;div>&NewLine;<div class&equals;"wp-post-navigation"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-pre"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;remove-duplicates-from-the-unsorted-singly-linked-list&sol;">Previous<&sol;a> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-next"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;find-and-break-a-loop-in-a-linked-list&sol;">Next<&sol;a> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;<&sol;div>&NewLine;<script type&equals;"text&sol;javascript">&NewLine;jQuery&lpar;document&rpar;&period;ready&lpar;function&lpar;&dollar;&rpar; &lbrace;&NewLine; &dollar;&period;post&lpar;'https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-admin&sol;admin-ajax&period;php'&comma; &lbrace;action&colon; 'mts&lowbar;view&lowbar;count'&comma; id&colon; '4277'&rcub;&rpar;&semi;&NewLine;&rcub;&rpar;&semi;&NewLine;<&sol;script>

Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

4 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

4 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

4 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

4 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

4 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

4 years ago