博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Leetcode】142. Linked List Cycle II
阅读量:7038 次
发布时间:2019-06-28

本文共 839 字,大约阅读时间需要 2 分钟。

142. Linked List Cycle II

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.

Follow up:

Can you solve it without using extra space?

思路

首先证明链表有环,再让一个指针从头开始,另一个指针从相遇的位置,每次都只走一步,相遇的地方就是链表的环开始的地方。

756310-20170627132541258-491029012.png

代码

public ListNode detectCycle(ListNode head) {    if (head == null) return null;    boolean flag = false;    ListNode fast = head, slow = head;    while (fast != null && fast.next != null) {        fast = fast.next.next;        slow = slow.next;        if (fast == slow) {            flag = true;            break;        }    }    if (!flag) return null;    slow = head;    while (true) {        //先判断,避免只有两个节点的环的情况        if (slow == fast) return slow;        slow = slow.next;        fast = fast.next;    }}

转载于:https://www.cnblogs.com/puyangsky/p/7084685.html

你可能感兴趣的文章