[Leetcode] Linked List Cycle II

来源:互联网 发布:centos ssh key登录 编辑:程序博客网 时间:2024/05/16 08:40

Reference: http://yucoding.blogspot.com/2013/12/leetcode-question-linked-list-cycle-ii.html

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.

/** * 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 slowNode = head;        ListNode fastNode = head;        while(fastNode != null) {            fastNode = nextNodeWithStrikeTwo(fastNode);            slowNode = nextNode(slowNode);            if(fastNode == null) {                return null;            }            if (fastNode == slowNode){                return findStartPoint(head, fastNode);            }        }        return null;    }        private ListNode nextNode(ListNode node) {        return node.next;    }        private ListNode nextNodeWithStrikeTwo(ListNode node) {        if (node.next == null) {            return null;        }        return node.next.next;    }        private ListNode findStartPoint(ListNode head, ListNode meetingNode) {        while(head != meetingNode) {            head = nextNode(head);            meetingNode = nextNode(meetingNode);        }        return head;    }}


0 0
原创粉丝点击