LeetCode刷题记录

LeetCode——141.环形链表

题目描述

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

示例1:
LeetCode刷题记录_第1张图片
示例2:
LeetCode刷题记录_第2张图片
示例3:
LeetCode刷题记录_第3张图片

分析:

参考:(整理的非常详细)
1.https://www.cnblogs.com/xudong-bupt/p/3667729.html
2.https://segmentfault.com/a/1190000008453411

代码展示:

/**
 * 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) {
        ListNode slow=head;
        ListNode fast=head;

        while(fast!=null && fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
            
            if(slow==fast){//如果快慢索引相等,说明存在环路.
                return true;
            }
        }
        return false;
    }
}

你可能感兴趣的:(LeetCode刷题)