

1.本题是力扣第142题-环形链表II的简化版,只需要判断是否有环,而不需要给出环的起始节点,所以只需要使用Floyd快慢指针就可以得出答案。完整代码如下:
1. /**
2. * Definition for singly-linked list.
3. * struct ListNode {
4. * int val;
5. * struct ListNode *next;
6. * };
7. */
8. // 判断链表是否存在环,快慢指针(Floyd判圈算法)
9. bool hasCycle(struct ListNode *head) {
10. // fast快指针,slow慢指针,都从头部出发
11. struct ListNode* fast = head;
12. struct ListNode* slow = head;
13. // 快指针和快指针下一个节点不为空时继续循环
14. while (fast && fast->next){
15. // 快指针一次走两步
16. fast = fast->next->next;
17. // 慢指针一次走一步
18. slow = slow->next;
19. // 快慢指针相遇,说明链表存在环
20. if (fast == slow) return true;
21. }
22. // 快指针走到NULL,链表无环
23. return false;
24. }
该算法时间复杂度为O(n),空间复杂度为O(1)。

1758

被折叠的 条评论
为什么被折叠?



