作者yam276 (史萊哲林的優等生)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Tue Sep 5 00:37:41 2023
141. Linked List Cycle
判斷Linked List是否是循環List
Solution:
用快慢指標來做
如果是循環List,總會有兩者一樣的一天
反之則會有人先變成nullptr
可以參考:
https://hackmd.io/@Hsins/fast-slow-pointers
Code:
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if(!head || !head->next)
return false;
ListNode* slow = head;
ListNode* fast = head->next;
while(slow != fast)
{
if(!fast || !fast->next)
return false;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.249.242 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1693845464.A.CAA.html
推 JerryChungYC: 大師 09/05 00:38
推 Che31128: 大師 09/05 00:39
推 DJYOSHITAKA: 終於有一題會了 09/05 00:47
推 ryanyee: 大師 09/05 00:47