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
}
相关推荐
一条大祥脚2 分钟前
26.1.3 快速幂+容斥 树上dp+快速幂 带前缀和的快速幂 正序转倒序 子序列自动机 线段树维护滑窗
数据结构·算法
二狗哈6 分钟前
czsc入门5: Tick RawBar(原始k线) NewBar (新K线)
算法·czsc
Tisfy11 分钟前
LeetCode 0865.具有所有最深节点的最小子树:深度优先搜索(一次DFS + Python5行)
算法·leetcode·深度优先·dfs·题解
Q741_14716 分钟前
C++ 队列 宽度优先搜索 BFS 力扣 429. N 叉树的层序遍历 C++ 每日一题
c++·算法·leetcode·bfs·宽度优先
Yzzz-F17 分钟前
P4145 上帝造题的七分钟 2 / 花神游历各国[线段树 区间开方(剪枝) + 区间求和]
算法·机器学习·剪枝
Zzz不能停19 分钟前
堆排序算法及大小堆区别
数据结构·算法
zd84510150029 分钟前
stm32f407 电机多轴联动算法
stm32·单片机·算法
代码游侠31 分钟前
应用——Linux FrameBuffer图形显示与多线程消息系统项目
linux·运维·服务器·开发语言·前端·算法
Eloudy32 分钟前
矩阵张量积(Kronecker积)的代数性质与定理
算法·量子计算
多米Domi01142 分钟前
0x3f 第25天 黑马web (145-167)hot100链表
数据结构·python·算法·leetcode·链表