141.环形链表

题目:环形链表 点击跳转

文章目录


题目描述

题目解答

java 复制代码
/**
 * 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 dummy = new ListNode(0);
        dummy.next = head;
        ListNode fast = dummy;
        ListNode slow = dummy;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                return true;
            }
        }
        return false;
    }
}

优化

java 复制代码
/**
 * 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 fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                return true;
            }
        }
        return false;
    }
}

注意事项


相关推荐
z2005093043 分钟前
今日算法(回溯子集)(模版题)
数据结构·算法·leetcode
QiLinkOS1 小时前
【用呼吸重构创造价值关系——QiLink生态】
c语言·数据结构·c++·人工智能·单片机·嵌入式硬件·算法
晚风予卿云月2 小时前
【前缀和】一维前缀和 & 二维前缀和
数据结构·c++·算法
YL200404262 小时前
071字符串解码
数据结构·leetcode
变量未定义~2 小时前
单点修改、区间求和(模板)、区间修改,单点查询(模板)
数据结构·算法
LinHenrY12273 小时前
数据结构(二叉树)
数据结构
炸薯条!4 小时前
树--二叉树--堆
数据结构
z200509304 小时前
今日算法(回溯子集)
数据结构·算法·leetcode
Hesionberger4 小时前
巧用异或找出唯一数字(多解)
java·数据结构·python·算法·leetcode
变量未定义~4 小时前
阶乘的约数和、斐波那契数列、数列区间最大值(ST表)
数据结构·算法