美文网首页
快慢指针 01

快慢指针 01

作者: 眼若繁星丶 | 来源:发表于2020-10-09 09:48 被阅读0次

    快慢指针 01


    LeetCode 141

    https://leetcode-cn.com/problems/linked-list-cycle/

    快慢指针

    快指针起始位置为头的下一个节点,慢指针起点在头位置,然后快指针每次跑两个节点,慢指针每次跑一个节点。

    如果没环,快指针会先跑完整个链表,然后结束循环。

    如果有环,快指针会先进入环中,并在环中一直转圈,慢指针迟早会进入环中,最终两指针一定会在环内节点相遇。

    细节:
    Q:为什么快慢指针的起点位置不都在头结点位置
    A:因为判断有环的条件是两指针相遇,所以刚开始的时候它们不能在同一起点,但是可以用do-while来解决这个问题。

    代码如下:

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null || head.next == null) return false;
            
            ListNode slow = head;
            ListNode fast = head.next;
            // 快指针的下一个位置有的走,则继续循环。
            while (fast != null && fast.next != null) {
                if (fast == slow) return true;
                slow = slow.next;
                fast = fast.next.next;
            }
            return false;
        }
    }

    相关文章

      网友评论

          本文标题:快慢指针 01

          本文链接:https://www.haomeiwen.com/subject/zlzkpktx.html