LeetCode 142. Linked List Cycle II

题目内容
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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值