142. Linked List Cycle II

来源:互联网 发布:java计算器实现 编辑:程序博客网 时间:2024/06/14 23:54

题目

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

代码

/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode DetectCycle(ListNode head) {        if(head==null) return null;        ListNode slow = head;        ListNode fast=head;        while(true ){            slow=slow.next;            if(fast==null || fast.next==null) return null;            fast=fast.next.next;            if(slow==fast)                break;        }        //to get the begining point for cycle, so another while needs        slow=head;        while(slow!=fast){            slow=slow.next;            fast=fast.next;        }         return slow;       }}

具体介绍说明,请参考地址:
http://www.jianshu.com/p/ce7f035daf74

原创粉丝点击