{"id":5325,"date":"2021-09-29T18:44:46","date_gmt":"2021-09-29T18:44:46","guid":{"rendered":"https:\/\/www.prepbytes.com\/blog\/?p=5325"},"modified":"2022-11-10T13:03:10","modified_gmt":"2022-11-10T13:03:10","slug":"detect-and-remove-the-loop-in-a-linked-list","status":"publish","type":"post","link":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/","title":{"rendered":"Detect and Remove the loop in a linked list"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png\" alt=\"\" \/><\/p>\n<p>In this article, we will learn to detect and remove loop in a linked list. A loop is a linked list defined as a condition that when the last node of the linked list doesn\u2019t point to the NULL.let\u2019s now try to understand the detection and removal of a loop in linked list.<\/p>\n<h3>Problem Statement<\/h3>\n<p>In this problem, we are given a singly linked list, which may contain a loop. We have to detect the loop, and if there is a loop, we need to remove it from the linked list.<\/p>\n<h3>Problem Statement Understanding to remove loop in linked list<\/h3>\n<p>The linked list contains a loop means the last node in the list will not be pointing to the NULL instead, it will be pointing to some other node in the list.<br \/>\n<img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/09\/p_1-33.png\" alt=\"\" \/><\/p>\n<p>Removing the loop means that the we need to make the last node of the list point to NULL instead of pointing to some other node in the list.<br \/>\n<img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/09\/p_2-32.png\" alt=\"\" \/><\/p>\n<p>Let&#8217;s understand how we can detect and remove loop in a linked list with the help of some examples.<\/p>\n<p>If the linked list given to us is:<br \/>\n<img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/09\/p_3-18.png\" alt=\"\" \/><\/p>\n<ul>\n<li>According to the problem statement, we need to detect and remove loop in a linked list.  <\/li>\n<li>From the linked list, we can see that there is a loop in the linked list starting at the node with value 0 and containing 4 nodes 0, 3, 0, and 1. The last node of the loop points back to the first node of the loop.<\/li>\n<li>Now, as we found out that there is a loop in the given linked list, so now we have to remove the loop from the linked list.<\/li>\n<li>So, the final linked list after removing the loop loop will be 1 &#8211; &gt; 0 &#8211; &gt; 3 &#8211; &gt; 0 &#8211; &gt; 1 -&gt; NULL<\/li>\n<\/ul>\n<p>Now I think from the above examples detection and removal of a loop in linked list is clear. So let\u2019s see how we can approach to remove loop in linked list<\/p>\n<p>Before moving to the approach section, try to think about how you can detect and remove loop in a linked list. What is the first thing that comes to your mind?<\/p>\n<ul>\n<li>\n<p>The very first thing that comes to mind is loop detection. Correct, but we can also use hashing to remove loop in linked list,. <\/p>\n<\/li>\n<li>\n<p>The hashing solution will require O(n) space for the creation of the hash table, so we are first going to look at hashing approach, and then jump to the efficient loop detection approach using Floyd\u2019s Cycle Detection Algorithm. <\/p>\n<\/li>\n<\/ul>\n<p>Try to think about how you can use hashing to detect and remove loop in a linked list ?<\/p>\n<p>Let us have a glance at the approach to get a clear look.<\/p>\n<h3>Approach 1 to remove loop in linked list  (Hashing)<\/h3>\n<p>This approach is going to be pretty simple. <\/p>\n<ul>\n<li>We are going to use an <strong>unordered_map<\/strong> and we will keep inserting nodes into it while traversing the linked list. <\/li>\n<li>Now, Once we encounter a node that is already present in the map, it will mean that we have reached the starting point of the loop.\n<ul>\n<li>Also, while iterating, we were maintaining two pointers at each step <strong>head<\/strong> and <strong>last<\/strong>, <strong>head<\/strong> pointing to the current node and <strong>last<\/strong> to the previous node of the current node.<\/li>\n<li>As now our <strong>head<\/strong> is pointing to the start node of the loop and as <strong>last<\/strong> was pointing to the previous node of the node to which <strong>head<\/strong> was pointing, i.e., it is pointing to the last node of the loop.<\/li>\n<li>So, now we will break the loop by making <strong>last-&gt;next == NULL<\/strong>.<\/li>\n<\/ul>\n<\/li>\n<li>In this way, the last loop node starts pointing to NULL instead of pointing to the starting node of the loop.<\/li>\n<\/ul>\n<h3>Code Implementation to detect and remove loop in a linked list<\/h3>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_5326 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_5326 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_5326 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_5326 .wpsm_nav-tabs > li.active > a, #tab_container_5326 .wpsm_nav-tabs > li.active > a:hover, #tab_container_5326 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_5326 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_5326 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_5326 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_5326 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_5326 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_5326 .wpsm_nav-tabs > li > a:hover , #tab_container_5326 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_5326 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_5326 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_5326 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_5326 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_5326 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_5326 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_5326 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_5326 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_5326 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_5326 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_5326 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_5326\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_5326\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_5326_1\" aria-controls=\"tabs_desc_5326_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C++<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_5326_2\" aria-controls=\"tabs_desc_5326_2\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Java<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_5326_3\" aria-controls=\"tabs_desc_5326_3\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_5326\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_5326_1\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"cpp\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n#include <bits stdc++.h>\r\nusing namespace std;\r\n \r\n\/* Node structure of the linked list node *\/\r\nstruct Node {\r\n    int key;\r\n    struct Node* next;\r\n};\r\n \r\n\/* Using this function we will be creating a new node of the linked list *\/\r\nNode* newNode(int key)\r\n{\r\n    Node* temp = new Node;\r\n    temp->key = key;\r\n    temp->next = NULL;\r\n    return temp;\r\n}\r\n\r\n\/* Using this function we will be printing the content of the linked list *\/\r\nvoid printList(Node* head)\r\n{\r\n    while (head != NULL) {\r\n        cout << head->key << \" \";\r\n        head = head->next;\r\n    }\r\n    cout << endl;\r\n}\r\n\r\n\/* Using this function we will be detecting and removing loop from the linked list *\/\r\nvoid hashAndRemove(Node* head)\r\n{\r\n    \r\n    unordered_map<node*, int=\"\"> node_map;\r\n\r\n    Node* last = NULL;\r\n    while (head != NULL) {\r\n       \r\n        if (node_map.find(head) == node_map.end()) {\r\n            node_map[head]++;\r\n            last = head;\r\n            head = head->next;\r\n        }\r\n        \r\n        else {\r\n            last->next = NULL;\r\n            break;\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    Node* head = newNode(1);\r\n    head->next = head;\r\n    head->next = newNode(0);\r\n    head->next->next = newNode(3);\r\n    head->next->next->next = newNode(0);\r\n    head->next->next->next->next = newNode(1);\r\n \r\n    head->next->next->next->next->next = head->next;\r\n\r\n    hashAndRemove(head);\r\n \r\n    printf(\"Linked List after removing loop : &#92;n\");\r\n    printList(head);\r\n \r\n    return 0;\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_5326_2\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"java\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\nimport java.util.*;\r\nclass DetectLoop {\r\n\r\n\tstatic Node head;\r\n\r\n\tstatic class Node {\r\n\t\tint data;\r\n\t\tNode next;\r\n\t\tNode(int d)\r\n\t\t{\r\n\t\t\tdata = d;\r\n\t\t\tnext = null;\r\n\t\t}\r\n\t}\r\n\tstatic public void push(int new_data)\r\n\t{\r\n\r\n\t\tNode new_node = new Node(new_data);\r\n\r\n\t\tnew_node.next = head;\r\n\r\n\t\thead = new_node;\r\n\t}\r\n\tvoid printList(Node node)\r\n\t{\r\n\t\twhile (node != null) {\r\n\t\t\tSystem.out.print(node.data + \" \");\r\n\t\t\tnode = node.next;\r\n\t\t}\r\n\t}\r\n\tstatic boolean removeLoop(Node h)\r\n\t{\r\n\t\tHashSet<Node> s = new HashSet<Node>();\r\n\t\tNode prev = null;\r\n\t\twhile (h != null) {\r\n\t\t\tif (s.contains(h)) {\r\n\t\t\t\tprev.next = null;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\ts.add(h);\r\n\t\t\t\tprev = h;\r\n\t\t\t\th = h.next;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\n\t\/* Driver program to test above function *\/\r\n\tpublic static void main(String[] args)\r\n\t{\r\n\t\tDetectLoop llist = new DetectLoop();\r\n\r\n\t\tllist.push(20);\r\n\t\tllist.push(4);\r\n\t\tllist.push(15);\r\n\t\tllist.push(10);\r\n\r\n\t\tllist.head.next.next.next.next = llist.head;\r\n\r\n\t\tif (removeLoop(head)) {\r\n\t\t\tSystem.out.println(\"Linked List after removing loop\");\r\n\t\t\tllist.printList(head);\r\n\t\t}\r\n\t\telse\r\n\t\t\tSystem.out.println(\"No Loop found\");\r\n\t}\r\n}\r\n\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_5326_3\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"Python\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"Python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\nclass Node:\r\n    def __init__(self, data, next=None):\r\n        self.data = data\r\n        self.next = next\r\n \r\ndef printList(head):\r\n    curr = head\r\n    while curr:\r\n        print(curr.data, end=' \u2014> ')\r\n        curr = curr.next\r\n    print('None')\r\n \r\n \r\ndef removeCycle(head):\r\n    prev = None        \r\n    curr = head        \r\n    s = set()\r\n    while curr:\r\n        if curr in s:\r\n            prev.next = None\r\n            return\r\n\r\n        s.add(curr)\r\n        prev = curr\r\n        curr = curr.next\r\n \r\nif __name__ == '__main__':\r\n \r\n    head = None\r\n    head = Node(1, head)\r\n    head = Node(0, head)\r\n    head = Node(3, head)\r\n    head = Node(0, head)\r\n    head = Node(1, head)\r\n \r\n    head.next.next.next.next.next = head.next\r\n \r\n    removeCycle(head)\r\n    printList(head)\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_5326 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_5326 a\"),jQuery(\"#tab-content_5326\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<h4>Output<\/h4>\n<p>Linked List after removing loop<br \/>\n1 0 3 0 1 <\/p>\n<p><strong>Time Complexity<\/strong> &#8211;  O(n), as list traversal is needed.<br \/>\n<strong>Space Complexity<\/strong> &#8211; O(n), the space required by the map.<\/p>\n<p>This approach to remove loop in linked list will work fine, but it requires extra O(n) space. So, now the main question is can we optimize this space?<\/p>\n<ul>\n<li>The answer is yes, and we will see how we can optimize this space in the next approach for detection and removal of a loop in linked list.<\/li>\n<\/ul>\n<p>Our next approach uses Floyd\u2019s Cycle Detection algorithm to remove loop in linked list. <\/p>\n<h3>Approach and Algorithm (Floyd\u2019s Cycle Detection) to detect and remove loop in a linked list<\/h3>\n<p>In this approach, we are going to use <strong>Floyd&#8217;s Cycle Detection algorithm<\/strong>. <\/p>\n<ol>\n<li>Firstly, we have to detect the loop in the given linked list.<\/li>\n<ul>\n<li>We know the most efficient algorithm for detecting a loop in any linked list is the <strong>Floyd Cycle detection Algorithm<\/strong>.<\/li>\n<\/ul>\n<li>In Floyd&#8217;s cycle detection algorithm, we initialize 2 pointers, <strong>slow<\/strong> and <strong>fast<\/strong>.<\/li>\n<ul>\n<li>Both initially point to the head of the list. <\/li>\n<li>The <strong>slow<\/strong> pointer jumps one place and the <strong>fast<\/strong> pointer jumps 2 places. <\/li>\n<li>If, at any point, <strong>slow<\/strong> and <strong>fast<\/strong> meet, it means that there exists a loop in the list. The point where <strong>slow<\/strong> and <strong>fast<\/strong> meet is somewhere inside the loop.<\/li>\n<\/ul>\n<li>Now, after detecting the loop, we will make <strong>slow<\/strong> point to the <strong>head<\/strong> and <strong>fast<\/strong> will be at its position only (Inside the loop).<\/li>\n<ul>\n<li>If still <strong>slow == fast<\/strong>, it means that the slow and fast met at the head node of the linked list.\n<ul>\n<li>So, in this case, we will run a while loop until <strong>fast-&gt;next != slow<\/strong> (inside loop move fast by one node at a time) and when <strong>fast-&gt;next == slow<\/strong>, we will remove the loop by making <strong>fast-&gt;next == NULL<\/strong>.<\/li>\n<\/ul>\n<\/li>\n<li>Now, if <strong>slow != fast<\/strong>, in this case, we will run a while loop until <strong>slow -&gt; next<\/strong> is not equal to <strong>fast -&gt; next<\/strong> (inside while loop move both <strong>slow<\/strong> and <strong>fast<\/strong> forward by 1 node), and when <strong>slow-&gt;next == fast-&gt;next<\/strong>, it means that <strong>fast<\/strong> is pointing to the last node of the loop, so we will remove the loop by making <strong>fast-&gt;next == NULL<\/strong>.<br \/>\n4) In this way, if there is any loop in the linked list, it will get removed.<\/li>\n<\/ul>\n<\/ol>\n<h3>Dry run to detect and remove loop in a linked list<\/h3>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/09\/p_5-6.png\" alt=\"\" \/><br \/>\n<img decoding=\"async\" src=\"https:\/\/prepbytes.com\/blog\/wp-content\/uploads\/2021\/09\/p_6-7.png\" alt=\"\" \/><\/p>\n<h3>Code Implementation to detect and remove loop in a linked list<\/h3>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_5327 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_5327 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_5327 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_5327 .wpsm_nav-tabs > li.active > a, #tab_container_5327 .wpsm_nav-tabs > li.active > a:hover, #tab_container_5327 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_5327 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_5327 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_5327 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_5327 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_5327 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_5327 .wpsm_nav-tabs > li > a:hover , #tab_container_5327 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_5327 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_5327 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_5327 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_5327 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_5327 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_5327 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_5327 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_5327 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_5327 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_5327 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_5327 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_5327\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_5327\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_5327_1\" aria-controls=\"tabs_desc_5327_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_5327_2\" aria-controls=\"tabs_desc_5327_2\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C++<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_5327_3\" aria-controls=\"tabs_desc_5327_3\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Java<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_5327\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_5327_1\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"C\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"c\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n#include&lt;stdio.h&gt;\r\n#include&lt;stdlib.h&gt;\r\n\r\nstruct Node {\r\n    int data;\r\n    struct Node* next;\r\n};\r\n \r\nvoid removeLoop(struct Node*, struct Node*);\r\n \r\nint detectAndRemoveLoop(struct Node* list)\r\n{\r\n    struct Node *slow_p = list, *fast_p = list;\r\n \r\n    while (slow_p &amp;&amp; fast_p &amp;&amp; fast_p-&gt;next) {\r\n        slow_p = slow_p-&gt;next;\r\n        fast_p = fast_p-&gt;next-&gt;next;\r\n \r\n        if (slow_p == fast_p) {\r\n            removeLoop(slow_p, list);\r\n \r\n            return 1;\r\n        }\r\n    }\r\n \r\n    return 0;\r\n}\r\n \r\nvoid removeLoop(struct Node* loop_node, struct Node* head)\r\n{\r\n    struct Node* ptr1 = loop_node;\r\n    struct Node* ptr2 = loop_node;\r\n \r\n    unsigned int k = 1, i;\r\n    while (ptr1-&gt;next != ptr2) {\r\n        ptr1 = ptr1-&gt;next;\r\n        k++;\r\n    }\r\n    ptr1 = head;\r\n \r\n    ptr2 = head;\r\n    for (i = 0; i &lt; k; i++)\r\n        ptr2 = ptr2-&gt;next;\r\n \r\n    while (ptr2 != ptr1) {\r\n        ptr1 = ptr1-&gt;next;\r\n        ptr2 = ptr2-&gt;next;\r\n    }\r\n \r\n    while (ptr2-&gt;next != ptr1)\r\n        ptr2 = ptr2-&gt;next;\r\n \r\n    ptr2-&gt;next = NULL;\r\n\t\r\n}\r\nvoid printList(struct Node* node)\r\n{\r\n    \/\/ Print the list after loop removal\r\n    while (node != NULL) {\r\n        printf(&quot;%d &quot;,node-&gt;data);\r\n        node = node-&gt;next;\r\n    }\r\n}\r\n \r\nstruct Node* newNode(int x)\r\n{\r\n    struct Node* node = malloc(sizeof(struct Node*));\r\n    node-&gt;data = x;\r\n    node-&gt;next = NULL;\r\n    return node;\r\n}\r\n \r\nint main()\r\n{\r\n    struct Node* head = newNode(50);\r\n    head-&gt;next = newNode(20);\r\n    head-&gt;next-&gt;next = newNode(15);\r\n    head-&gt;next-&gt;next-&gt;next = newNode(4);\r\n    head-&gt;next-&gt;next-&gt;next-&gt;next = newNode(10);\r\n \r\n    head-&gt;next-&gt;next-&gt;next-&gt;next-&gt;next = head-&gt;next-&gt;next;\r\n \r\n    detectAndRemoveLoop(head);\r\n \r\n    printf(&quot;Linked List after removing loop &#92;n&quot;);\r\n    printList(head);\r\n    return 0;\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_5327_2\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"cpp\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\n#include &lt;bits stdc++.h&gt;\r\nusing namespace std;\r\n \r\n\/* Node structure of the linked list node *\/\r\nstruct Node {\r\n    int key;\r\n    struct Node* next;\r\n};\r\n\r\n\/* Using this function we will be creating a new node of the linked list *\/\r\nNode* newNode(int key)\r\n{\r\n    Node* temp = new Node;\r\n    temp-&gt;key = key;\r\n    temp-&gt;next = NULL;\r\n    return temp;\r\n}\r\n\r\n\/* Using this function we will be printing the content of the linked list *\/\r\nvoid printList(Node* head)\r\n{\r\n    while (head != NULL) {\r\n        cout &lt;&lt; head-&gt;key &lt;&lt; &quot; &quot;;\r\n        head = head-&gt;next;\r\n    }\r\n    cout &lt;&lt; endl;\r\n}\r\n\r\n\/* Using this function we will be detecting and removing loop from the linked list *\/\r\nvoid detectAndRemoveLoop(Node* head)\r\n{\r\n\r\n    if (head == NULL || head-&gt;next == NULL)\r\n        return;\r\n \r\n    Node *slow = head, *fast = head;\r\n\r\n    slow = slow-&gt;next;\r\n    fast = fast-&gt;next-&gt;next;\r\n\r\n    while (fast &amp;&amp; fast-&gt;next) {\r\n        if (slow == fast)\r\n            break;\r\n        slow = slow-&gt;next;\r\n        fast = fast-&gt;next-&gt;next;\r\n    }\r\n \r\n    \/* If loop exists *\/\r\n    if (slow == fast)\r\n    {\r\n        slow = head;\r\n\r\n          if(slow == fast) {\r\n              while(fast-&gt;next != slow) fast = fast-&gt;next;\r\n        }\r\n          else {\r\n            while (slow-&gt;next != fast-&gt;next) {\r\n                slow = slow-&gt;next;\r\n                fast = fast-&gt;next;\r\n            }\r\n        }\r\n \r\n        fast-&gt;next = NULL; \r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    Node* head = newNode(1);\r\n    head-&gt;next = head;\r\n    head-&gt;next = newNode(0);\r\n    head-&gt;next-&gt;next = newNode(3);\r\n    head-&gt;next-&gt;next-&gt;next = newNode(0);\r\n    head-&gt;next-&gt;next-&gt;next-&gt;next = newNode(1);\r\n\r\n    head-&gt;next-&gt;next-&gt;next-&gt;next-&gt;next = head-&gt;next;\r\n \r\n    detectAndRemoveLoop(head);\r\n \r\n    printf(&quot;Linked List after removing loop : &#92;n&quot;);\r\n    printList(head);\r\n \r\n    return 0;\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_5327_3\">\r\n\t\t\t\t\t\t\t\t<!-- wp:enlighter\/codeblock {\"language\":\"java\"} -->\r\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\r\npublic class LinkedList {\r\n\r\n    static Node head;\r\n    \r\n    \/* Node structure of the linked list node *\/\r\n    static class Node {\r\n\r\n        int data;\r\n        Node next;\r\n\r\n        Node(int d)\r\n        {\r\n            data = d;\r\n            next = null;\r\n        }\r\n    }\r\n    \r\n    \/* Using this function we will be detecting and removing loop from the linked list *\/\r\n    void detectAndRemoveLoop(Node node)\r\n    {\r\n\r\n        if (node == null || node.next == null)\r\n            return;\r\n\r\n        Node slow = node, fast = node;\r\n\r\n        slow = slow.next;\r\n        fast = fast.next.next;\r\n\r\n        while (fast != null &amp;&amp; fast.next != null) {\r\n            if (slow == fast)\r\n                break;\r\n\r\n            slow = slow.next;\r\n            fast = fast.next.next;\r\n        }\r\n\r\n        if (slow == fast) {\r\n            slow = node;\r\n            if (slow != fast) {\r\n                while (slow.next != fast.next) {\r\n                    slow = slow.next;\r\n                    fast = fast.next;\r\n                }\r\n\r\n                fast.next = null; \r\n            }\r\n\r\n            else {\r\n                while(fast.next != slow) {\r\n                    fast = fast.next;\r\n                }\r\n                fast.next = null;\r\n            }\r\n        }\r\n    }\r\n    \r\n    \/* Using this function we will be printing the content of the linked list *\/\r\n    void printList(Node node)\r\n    {\r\n        while (node != null) {\r\n            System.out.print(node.data + &quot; &quot;);\r\n            node = node.next;\r\n        }\r\n    }\r\n\r\n    public static void main(String[] args)\r\n    {\r\n        LinkedList list = new LinkedList();\r\n        list.head = new Node(1);\r\n        list.head.next = new Node(0);\r\n        list.head.next.next = new Node(3);\r\n        list.head.next.next.next = new Node(0);\r\n        list.head.next.next.next.next = new Node(1);\r\n\r\n        head.next.next.next.next.next = head.next;\r\n        list.detectAndRemoveLoop(head);\r\n        System.out.println(&quot;Linked List after removing loop : &quot;);\r\n        list.printList(head);\r\n    }\r\n}\r\n<\/pre>\r\n<!-- \/wp:enlighter\/codeblock -->\r\n\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_5327 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_5327 a\"),jQuery(\"#tab-content_5327\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<p><strong>Output<\/strong>:<br \/>\nLinked List after removing loop :<br \/>\n1 0 3 0 1<\/p>\n<p><strong>Time Complexity<\/strong>: O(n), as list traversal is needed.<\/p>\n<p>So, in this article, we have explained how to detect and remove the loop in a linked list. We have explained both approaches i.e.hashing and Floyd\u2019s Cycle Detection algorithm with picturised dry run and code implementation as well.This is one of the most important question asked in interviews .If you want to practice more questions on linked lists feel free to solve them at <a href=\"https:\/\/mycode.prepbytes.com\/interview-coding\/practice\/linked-list\">Prepbytes (Linked Lists)<\/a>.<\/p>\n<h2>FAQs to remove loop in linked list<\/h2>\n<p><ol><strong><\/p>\n<li>Explain the type of memory allocation in linked list?<\/li>\n<p><\/strong><br \/>\nDynamic memory allocation is used to allocate memory in linked lists.<br \/>\n<strong><\/p>\n<li>Can we access the random element of the linked list?<\/li>\n<p><\/strong><br \/>\nWe can not access any node directly, if we want to access any node then we have the traverse the linked list.<br \/>\n<strong><\/p>\n<li>Is it possible to find a loop in linked list time complexity?<\/li>\n<p><\/strong><br \/>\nBasically complexity is not counted by the number of loop steps,but the nodes visite<\/ol><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn to detect and remove loop in a linked list. A loop is a linked list defined as a condition that when the last node of the linked list doesn\u2019t point to the NULL.let\u2019s now try to understand the detection and removal of a loop in linked list. Problem Statement [&hellip;]<\/p>\n","protected":false},"author":52,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[125],"tags":[],"class_list":["post-5325","post","type-post","status-publish","format-standard","hentry","category-linked-list"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Detect and Remove the loop in a linked list | Linked list articles | PrepBytes Blog<\/title>\n<meta name=\"description\" content=\"Learn the most efficient way to detect and remove the loop in a linked list.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Detect and Remove the loop in a linked list | Linked list articles | PrepBytes Blog\" \/>\n<meta property=\"og:description\" content=\"Learn the most efficient way to detect and remove the loop in a linked list.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/\" \/>\n<meta property=\"og:site_name\" content=\"PrepBytes Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prepbytes0211\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-09-29T18:44:46+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-11-10T13:03:10+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png\" \/>\n<meta name=\"author\" content=\"Prepbytes\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prepbytes\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/\"},\"author\":{\"name\":\"Prepbytes\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e\"},\"headline\":\"Detect and Remove the loop in a linked list\",\"datePublished\":\"2021-09-29T18:44:46+00:00\",\"dateModified\":\"2022-11-10T13:03:10+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/\"},\"wordCount\":1241,\"commentCount\":0,\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png\",\"articleSection\":[\"Linked list articles\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/\",\"url\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/\",\"name\":\"Detect and Remove the loop in a linked list | Linked list articles | PrepBytes Blog\",\"isPartOf\":{\"@id\":\"http:\/\/43.205.93.38\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png\",\"datePublished\":\"2021-09-29T18:44:46+00:00\",\"dateModified\":\"2022-11-10T13:03:10+00:00\",\"description\":\"Learn the most efficient way to detect and remove the loop in a linked list.\",\"breadcrumb\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#primaryimage\",\"url\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png\",\"contentUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/43.205.93.38\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Linked list articles\",\"item\":\"https:\/\/prepbytes.com\/blog\/category\/linked-list\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Detect and Remove the loop in a linked list\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/43.205.93.38\/#website\",\"url\":\"http:\/\/43.205.93.38\/\",\"name\":\"PrepBytes Blog\",\"description\":\"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING\",\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/43.205.93.38\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"http:\/\/43.205.93.38\/#organization\",\"name\":\"Prepbytes\",\"url\":\"http:\/\/43.205.93.38\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"contentUrl\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"width\":160,\"height\":160,\"caption\":\"Prepbytes\"},\"image\":{\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/prepbytes0211\/\",\"https:\/\/www.instagram.com\/prepbytes\/\",\"https:\/\/www.linkedin.com\/company\/prepbytes\/\",\"https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA\"]},{\"@type\":\"Person\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e\",\"name\":\"Prepbytes\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g\",\"caption\":\"Prepbytes\"},\"url\":\"https:\/\/prepbytes.com\/blog\/author\/gourav-jaincollegedekho-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Detect and Remove the loop in a linked list | Linked list articles | PrepBytes Blog","description":"Learn the most efficient way to detect and remove the loop in a linked list.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/","og_locale":"en_US","og_type":"article","og_title":"Detect and Remove the loop in a linked list | Linked list articles | PrepBytes Blog","og_description":"Learn the most efficient way to detect and remove the loop in a linked list.","og_url":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/","og_site_name":"PrepBytes Blog","article_publisher":"https:\/\/www.facebook.com\/prepbytes0211\/","article_published_time":"2021-09-29T18:44:46+00:00","article_modified_time":"2022-11-10T13:03:10+00:00","og_image":[{"url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png","type":"","width":"","height":""}],"author":"Prepbytes","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Prepbytes","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#article","isPartOf":{"@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/"},"author":{"name":"Prepbytes","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e"},"headline":"Detect and Remove the loop in a linked list","datePublished":"2021-09-29T18:44:46+00:00","dateModified":"2022-11-10T13:03:10+00:00","mainEntityOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/"},"wordCount":1241,"commentCount":0,"publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png","articleSection":["Linked list articles"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/","url":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/","name":"Detect and Remove the loop in a linked list | Linked list articles | PrepBytes Blog","isPartOf":{"@id":"http:\/\/43.205.93.38\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#primaryimage"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png","datePublished":"2021-09-29T18:44:46+00:00","dateModified":"2022-11-10T13:03:10+00:00","description":"Learn the most efficient way to detect and remove the loop in a linked list.","breadcrumb":{"@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#primaryimage","url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png","contentUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1645009130055-Article_178.png"},{"@type":"BreadcrumbList","@id":"https:\/\/prepbytes.com\/blog\/detect-and-remove-the-loop-in-a-linked-list\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/43.205.93.38\/"},{"@type":"ListItem","position":2,"name":"Linked list articles","item":"https:\/\/prepbytes.com\/blog\/category\/linked-list\/"},{"@type":"ListItem","position":3,"name":"Detect and Remove the loop in a linked list"}]},{"@type":"WebSite","@id":"http:\/\/43.205.93.38\/#website","url":"http:\/\/43.205.93.38\/","name":"PrepBytes Blog","description":"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING","publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/43.205.93.38\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"http:\/\/43.205.93.38\/#organization","name":"Prepbytes","url":"http:\/\/43.205.93.38\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/","url":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","contentUrl":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","width":160,"height":160,"caption":"Prepbytes"},"image":{"@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/prepbytes0211\/","https:\/\/www.instagram.com\/prepbytes\/","https:\/\/www.linkedin.com\/company\/prepbytes\/","https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA"]},{"@type":"Person","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e","name":"Prepbytes","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g","caption":"Prepbytes"},"url":"https:\/\/prepbytes.com\/blog\/author\/gourav-jaincollegedekho-com\/"}]}},"_links":{"self":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/5325","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/users\/52"}],"replies":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/comments?post=5325"}],"version-history":[{"count":6,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/5325\/revisions"}],"predecessor-version":[{"id":10444,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/5325\/revisions\/10444"}],"wp:attachment":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/media?parent=5325"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/categories?post=5325"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/tags?post=5325"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}