142. Linked List Cycle II(java)

来源:互联网 发布:linux批量ping的命令 编辑:程序博客网 时间:2024/05/29 19:39

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.

public class Solution {    public ListNode detectCycle(ListNode head) {        ListNode fast = head;        ListNode slow = head;        while (true) {        if (fast == null || fast.next == null) return null;           slow = slow.next;        fast = fast.next.next;        if (fast == slow) break;        }        //if(head==null||head.next==null||head.next.next==null) return null ;        //ListNode fast = head;        //ListNode slow = head;        //while(fast.next!=null&&fast.next.next!=null){            //fast=fast.next.next;            //slow=slow.next;            //if (fast==slow) break;}        slow = head;        while(slow!=head){            slow=slow.next;            fast=fast.next; }        return slow;     }}

原创粉丝点击