首页 > 其他 > 详细

leetcode - 快慢指针(链表)

时间:2020-12-26 10:18:52      阅读:36      评论:0      收藏:0      [点我收藏+]

对于快慢指针 可以用来检测链表是否存在环的情况;

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

其核心点在于 通过 慢指针是否能等于快指针 的判断 来检测 当前链表是否存在环;

/**
 * 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;
        }
        // 使用快慢指针
        // 将head作为慢指针
        ListNode slow = head;
        // 将head.next作为快指针
        ListNode fast = head.next;
        // 当快指针不等于慢指针情况下,继续遍历
        while (slow != fast) {
            // 直到快指针为空或快指针的下一个节点为空的情况下表示遍历结束
            if (fast == null || fast.next == null) {
                return false;
            }
            // 迭代慢指针
            slow = slow.next;
            // 迭代快指针
            fast = fast.next.next;
        }
        // 当执行到当前位置表示慢指针遇到了快指针
        return true;
    }
}

 

leetcode - 快慢指针(链表)

原文:https://www.cnblogs.com/xingguoblog/p/14189321.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!