日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

[LeetCode] Linked List Cycle II

發布時間:2025/4/9 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode] Linked List Cycle II 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

解題思路

設鏈表長度為n,頭結點與循環節點之間的長度為k。定義兩個指針slow和fast,slow每次走一步,fast每次走兩步。當兩個指針相遇時,有:

  • fast = slow * 2
  • fast - slow = (n - k)的倍數
    由上述兩個式子能夠得到slow為(n-k)的倍數

兩個指針相遇后,slow指針回到頭結點的位置,fast指針保持在相遇的節點。此時它們距離循環節點的距離都為k,然后以步長為1遍歷鏈表,再次相遇點即為循環節點的位置。

實現代碼

/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*///Runtime:16 ms class Solution { public:ListNode *detectCycle(ListNode *head) {if (head == NULL){return NULL;}ListNode *slow = head;ListNode *fast = head;while (fast->next && fast->next->next){slow = slow->next;fast = fast->next->next;if (fast == slow){break;}}if (fast->next && fast->next->next){slow = head;while (slow != fast){slow = slow->next;fast = fast->next;}return slow;}return NULL;} };

轉載于:https://www.cnblogs.com/blfbuaa/p/7049933.html

總結

以上是生活随笔為你收集整理的[LeetCode] Linked List Cycle II的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。