LeetCode-Linked List Cycle II

来源:互联网 发布:贤友板材优化软件 编辑:程序博客网 时间:2024/04/30 14:46
作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/24018961
时间:2014-4-19

题目

Linked List Cycle II

 Total Accepted: 10764 Total Submissions: 35294My Submissions

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?

 Definition for singly-linked list. public class ListNode {     int val;     ListNode next;     ListNode(int x) {         val = x;         next = null;     } } 

想法:

见《cracking the code interview》P126 中文版
1.一个一步走的slow指针,一个两步走的fast指针
2.如果有环,slow 与fast 一定碰面(如果刚好错过,一定是错过一步(并且是fast(K+1)领先slow(K-1),K为环中从相交点开始计算的数字),但是,他们的上一步(均为k-1)正好相遇)
3.假设Fast走了2N步,那么slow走了N步。
如果环一共有M个节点,当
/** * 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 slow = head;        ListNode fast = head;        if(head == null || head.next == null)            return null;        while(fast != null && fast.next != null){            slow = slow.next;            fast = fast.next.next;            if(slow == fast)                break;        }        if(fast == null || fast.next == null)            return null;        slow = head;        while(slow != fast){            slow = slow.next;            fast = fast.next;        }        return fast;    }}




返回

LeetCode Solution(持续更新,java>c++)

0 0
原创粉丝点击