【LeetCode】141. Linked List Cycle 解题记录
问题描述
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
测试样例
1 | Input: head = [3,2,0,-4], pos = 1 |
1 | Input: head = [1,2], pos = 0 |
1 | Input: head = [1], pos = -1 |
说明
1 | The number of the nodes in the list is in the range [0, 10^4]. |
解题
思路
使用快慢指针:
- 若链表可达 null 则无环
- 若快指针套圈慢指针则有环
补充:
- 双指针
- 快慢指针
- 时间复杂度
O(n)
代码
1 | /** |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 哆啦 C 梦!
评论