当前位置: 代码迷 >> 综合 >> LeetCode 142. Linked List Cycle II
  详细解决方案

LeetCode 142. Linked List Cycle II

热度:89   发布时间:2023-10-09 14:13:10.0

Linked List Cycle II


题目思路

判断给定链表中是否存在环,如果存在环返回环的起点。

参考这篇文章。


题目代码:

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


  相关解决方案