【LeetCode-面试算法经典-Java实现】【142-Linked List Cycle II(单链表中有环II)】

126 篇文章 82 订阅

【142-Linked List Cycle II(单链表中有环II)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】

原题

  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?

题目大意

  给定一个单链表,如果它有环,返回环入口的第一个节点,否则返回null

解题思路

  先判断链表是否有环,使用快(fast)慢指针(slow),解法见【141-Linked List Cycle(单链表中有环)】,如果没有环就返回null,如果有环,有fast=slow,就让让slow重新指向链表头,然后两个指针每次同时移动一个位置,直到两链表相遇,相遇点就是环的入口结点。

代码实现

结点类

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;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;

            if (fast == slow) {
                break;
            }
        }

        if (fast == null || fast.next == null) {
            return null;
        }

        slow = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }

        return slow;
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

这里写图片描述

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47774563

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值