()
| 244 | } |
| 245 | |
| 246 | public static void removeCycle() { |
| 247 | //detect cycle |
| 248 | Node slow = head; |
| 249 | Node fast = head; |
| 250 | boolean cycle = false; |
| 251 | while(fast != null && fast.next != null) { |
| 252 | slow = slow.next; |
| 253 | fast = fast.next.next; |
| 254 | if(fast == slow) { |
| 255 | cycle = true; |
| 256 | break; |
| 257 | } |
| 258 | } |
| 259 | if(cycle == false) { |
| 260 | return; |
| 261 | } |
| 262 | |
| 263 | //find meeting point |
| 264 | slow = head; |
| 265 | Node prev = null; //last node |
| 266 | while(slow != fast) { |
| 267 | prev = fast; |
| 268 | slow = slow.next; |
| 269 | fast = fast.next; |
| 270 | } |
| 271 | |
| 272 | //remove cycle -> last.next = null |
| 273 | prev.next = null; |
| 274 | } |
| 275 | |
| 276 | private Node getMid(Node head) { |
| 277 | Node slow = head; |
nothing calls this directly
no outgoing calls
no test coverage detected