[LeetCode]141. Linked List Cycle 解题报告(C++)
题目描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目大意
- 给一个单链表. 让你检查是否存在环.
解题思路
方法1:
- 快慢指针.
- 慢指针每次走一步.快指针每次走两步.若二者相遇则存在环.
- 否则不存在环.
代码实现:
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow, *fast;
slow = head;
fast = head;
while (fast&&fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}
};