LeetCode 142. Linked List Cycle II

来源:互联网 发布:淘宝天下天下网商区别 编辑:程序博客网 时间:2024/06/08 15:45

题目内容
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
题目分析
在141题的基础上,加入了寻找出了环的起点位置,如果有环找出起点,没有环返回null。
找出环的起点,当找到确定有环以后,讲fast标记回head结点,然后步长调整为1,当再次与slow相遇的时候,就是环的开始结点。,参考
单链表判断环

存在问题 这样写有一个问题,就是无法判断环为1-2-1,起始结点即为环的开始结点,且环的大小为2 的情况,需要单独判断。

这个在代码2中也是要判断的,只是代码2特别精简。可以直接读代码2.

代码如下

/** * 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 fast=head;        ListNode slow=head;        boolean flag=false;        while(fast!=null&&fast.next!=null)        {            fast=fast.next.next;            slow=slow.next;            if (slow==fast) {                flag=true;                break;            }                   }        if (flag==true) {            fast=head;            if (slow==fast) {                    return fast;                }               while(fast!=null&&fast.next!=null)            {                fast=fast.next;                slow=slow.next;                if (slow==fast) {                    return fast;                }                       }        }        return null;    }}

代码2

public ListNode detectCycle(ListNode head) {    if (head == null || head.next == null) {        return null;   // no circle    }    ListNode slow = head, fast = head;    while (fast != null && fast.next != null) {        fast = fast.next.next;        slow = slow.next;        if (fast == slow) {  // circle detected            while (head != fast) {                fast = fast.next;                head = head.next;            }            return head;        }    }    return null; // no circle}
0 0