Linked List Cycle II Java

来源:互联网 发布:错误推算法 编辑:程序博客网 时间:2024/06/06 21:35
/*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?*///Runner Technique Again//Two points: slow and fast, //1.slow: move one step at time//2.fast: move two steps at time//3.while two points(slow and fast) are encounter => hasCycle => break//4.Set slow point back to head to find node point of cycle begin. public class Solution {    public ListNode detectCycle(ListNode head) {    if (head == null)return null;if (head.next == null)return null;//handle the base case of {1} tail connects to head itselfif(head.next ==head) return head;ListNode slow = head;ListNode fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;if (slow == fast) {break;}}//handle the case of noCycle that make sure there is cycle existif(slow==null || fast ==null || fast.next==null){return null;}//move slow point to the headslow=head;while(slow!=fast){slow=slow.next;fast=fast.next;}//when two point slow and fast encounter again, //return either slow or fast for point of cycle begin return slow;    }}

0 0
原创粉丝点击