Linked List Cycle II

来源:互联网 发布:qq飞车幻灵奇迹数据 编辑:程序博客网 时间:2024/06/16 03:34
/** * 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) {        if (head == null){            return null;        }        ListNode slow = head;        ListNode fast = head;        int count = 0;        while(true){            if (fast.next == null || fast.next.next == null){                return null;            }            count++;            slow = slow.next;            fast = fast.next.next;            if (slow == fast){                break;            }        }        slow = head;        fast = head;        for (int i=0;i<count;i++){            fast = fast.next;        }        while(true){            if (slow == fast){                return slow;            }            slow = slow.next;            fast = fast.next;        }    }}
0 0
原创粉丝点击