141. Linked List Cycle
1、原题
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
2、题意解析与思路
这道题就是让我们判断一个链表中存不存在环的问题。这个问题比较简单,我们可以使用快慢指针来判断,我们设定一个快指针和一个慢指针。当链表中存在环时,快指针终将会追上慢指针。通过这点我们就可以完成这一道题目了。
3、代码
bool hasCycle(ListNode *head) {
ListNode *fast = head, *low = head;
int i;
while (low != NULL) {
i = 3;
while (i) {
if (fast == null) {
return false;
}
fast = fast->next;
if (fast == low) {
return true;
}
i--;
}
low = low->next;
}
return false;
}