(Node head)
| 121 | |
| 122 | class ans { |
| 123 | public static void removeLoop(Node head) { |
| 124 | if (head == null || head.next == null) |
| 125 | return; |
| 126 | |
| 127 | Node slow = head, fast = head; |
| 128 | |
| 129 | // Search for loop using slow and fast pointers |
| 130 | while (fast != null && fast.next != null) { |
| 131 | slow = slow.next; |
| 132 | fast = fast.next.next; |
| 133 | |
| 134 | if (slow == fast) { |
| 135 | remove(head, fast, slow); |
| 136 | break; |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | private static void remove(Node head, Node fast, Node slow) { |
| 142 | if (slow == fast) { |