leetcode--Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { ListNode entry = null; boolean flag = true; if(head != null){ ListNode speedOne = head; ListNode speedTwo = head; if(head.next != null){ speedOne = speedOne.next; if(speedOne.next != null) speedTwo = speedOne.next; else flag = false; } else flag = false; while(flag){ if(speedOne == speedTwo) break; else{ speedOne = speedOne.next; if(speedTwo != null && speedTwo.next != null){ speedTwo = speedTwo.next; speedTwo = speedTwo.next; } else{ flag = false; break; } } } if(flag){ speedOne = head; while(speedOne != speedTwo){ speedOne = speedOne.next; speedTwo = speedTwo.next; } entry = speedOne; } else entry = null; } return entry; } }
rewrite the code as the following:
public class Solution { public ListNode detectCycle(ListNode head) { //find the intersection ListNode of speed one and speed two ListNode intersectNode = null; if(head != null && head.next != null){ ListNode speedOne = head; ListNode speedTwo = head.next; while(speedTwo != null){ if(speedOne == speedTwo) break; speedOne = speedOne.next; speedTwo = speedTwo.next; if(speedTwo != null) speedTwo = speedTwo.next; } //Once speedTwo meets speedOne, we reset speedOne to head and change //the speed of speedTwo to one if(speedTwo != null){ speedOne = head; speedTwo = speedTwo.next; while(speedOne != speedTwo){ speedOne = speedOne.next; speedTwo = speedTwo.next; } intersectNode = speedOne; } } return intersectNode; } }