LeetCode //C - 141. Linked List Cycle

141. Linked List Cycle

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

Input: head = 3,2,0,-4, pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

Input: head = 1,2, pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

Input: head = 1, pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range 0 , 1 0 4 0, 10\^4 0,104.
  • − 1 0 5 < = N o d e . v a l < = 1 0 5 -10^5 <= Node.val <= 10^5 −105<=Node.val<=105
  • pos is -1 or a valid index in the linked-list.

From: LeetCode

Link: 141. Linked List Cycle


Solution:

Ideas:

Fundamental Idea:

Imagine two runners on a circular track, one runner (the hare) is much faster than the other (the tortoise). If they start at the same position and run in the same direction, the faster runner (hare) will eventually lap the slower runner (tortoise). Similarly, in a linked list, if there is a cycle, a faster pointer will eventually meet the slower pointer within the cycle.

Code Explanation:

1. Initialization:

  • We have two pointers: tortoise (slow-moving) and hare (fast-moving). Both start at the head of the linked list.

2. Movement:

  • The tortoise moves one step at a time (tortoise = tortoise->next).
  • The hare moves two steps at a time (hare = hare->next->next).

3. Checking for Cycle:

  • If there is no cycle in the linked list, the hare (which moves faster) will eventually reach the end of the list and encounter a NULL pointer.
  • If there is a cycle, the hare will eventually "lap" the tortoise, and they will meet at some point inside the cycle.

4. Loop Termination:

  • The loop continues as long as hare and hare->next are not NULL.
  • If tortoise and hare pointers meet (tortoise == hare), it indicates the presence of a cycle, and the function returns true.
  • If the loop ends without the pointers meeting, there is no cycle, and the function returns false.
Code:
c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

bool hasCycle(struct ListNode *head) {
    if (!head) return false; // If list is empty
    
    struct ListNode *tortoise = head;  // Slow pointer
    struct ListNode *hare = head;      // Fast pointer

    while (hare != NULL && hare->next != NULL) {
        tortoise = tortoise->next;          // Move slow pointer one step
        hare = hare->next->next;            // Move fast pointer two steps
        
        if (tortoise == hare) return true;  // If they meet, there's a cycle
    }

    return false;  // If loop exits, there's no cycle
}
相关推荐
持力行3 小时前
从C struct到C++中的class
c语言·c++
:-)5 小时前
算法-归并排序
java·开发语言·数据结构·算法·排序算法
2501_914245938 小时前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
Jerry9 小时前
LeetCode 101. 对称二叉树
算法
可编程芯片开发10 小时前
基于MPPT最大功率跟踪的离网光伏发电系统Simulink建模与仿真
算法
AI科技星10 小时前
线性算子不是空间映射函数,是全域双螺旋场之间拉伸、旋转、耦合、坍缩的跨空间标准化变换载体《全域数学vs传统数学:人类文明进阶200讲》第80讲
线性代数·算法·矩阵·数据挖掘·回归·乖乖数学·全域数学
米罗篮10 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
2501_9142459311 小时前
C语言与硬件交互:从GPIO到中断的嵌入式编程实践
c语言·单片机·交互
dream_home840711 小时前
图像算法模型NPU适配与算法服务实战指南
人工智能·python·算法·npu 图像服务
大鱼>11 小时前
多宠物家庭智能管理平台:云端架构与多设备协同实战
python·算法·iot·宠物