Leedcode10-linked-list-cycle-ii
发布日期:2025-04-04 18:30:35 浏览次数:12 分类:精选文章

本文共 1360 字,大约阅读时间需要 4 分钟。

判断是否为循环链表,并返回第一个结点

要判断一个链表是否为循环链表,可以使用快慢指针法。通过比较两个指针的速度,我们可以确定是否存在环。如果存在环,则返回该环的起始节点。

判断循环链表的方法

  • 快慢指针法

    • 初始化两个指针 fastslow,均指向链表的头节点。
    • fast 指针每次移动两步,slow 指针每次移动一步。
    • fastslow 相遇时,说明链表存在环。
  • 断开环的方法

    • 当存在环时,从头节点开始,逐个遍历节点,断开每个节点的 next 指针,直到 nextnull
    • 断开之后,剩下的头节点即为环的起始节点。
  • 代码实现

    #include 
    #include
    using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};class Solution {public: bool hasCycle(ListNode *head) { if (head == NULL) { return false; } if (head->next == NULL) { return false; } ListNode *fast = head; ListNode *slow = head; while (fast->next != NULL && fast->next->next != NULL) { fast = fast->next->next; slow = slow->next; if (fast == slow) { return true; } } return false; } ListNode *detectCycle(ListNode *head) { if (!hasCycle(head)) { return NULL; } ListNode *temp = head; while (head->next != NULL) { temp = head->next; head->next = NULL; head = temp; } return head; }};

    代码解释

    • hasCycle函数:使用快慢指针法判断是否存在环。当 fastslow 指针相遇时,返回 true,否则返回 false
    • detectCycle函数:当存在环时,通过断开环的方式找到环的起始节点。逐个断开节点的 next 指针,直到 nextnull,剩下的头节点即为环的起始节点。
    上一篇:Leedcode12-word-break-i
    下一篇:Leedcode1-求树的最小高度

    发表评论

    最新留言

    路过,博主的博客真漂亮。。
    [***.116.15.85]2025年04月20日 06时18分50秒