In this program, we are going to share a Java program to detect and remove the loop in the linked list. If you are a Java beginner and want to start learning the Java programming, then keep your close attention in this tutorial as I am going to share how to write a Java program to detect and remove the loop in linked list.
To increase your Java knowledge, practice all Java programs:
Copy the below Java program and execute it with the help of Javac compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } int detectAndRemoveLoop(Node node) { Node slow = node, fast = node; while (slow != null && fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { removeLoop(slow, node); return 1; } } return 0; } void removeLoop(Node loop, Node curr) { Node ptr1 = null, ptr2 = null; ptr1 = curr; while (1 == 1) { ptr2 = loop; while (ptr2.next != loop && ptr2.next != ptr1) { ptr2 = ptr2.next; } if (ptr2.next == ptr1) { break; } ptr1 = ptr1.next; } ptr2.next = null; } void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(50); list.head.next = new Node(20); list.head.next.next = new Node(15); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(10); head.next.next.next.next.next = head.next.next; list.detectAndRemoveLoop(head); System.out.println("Linked List after removing loop : "); list.printList(head); } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.