141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
对于LeetCode上,使用这个方法是没法通过的,随时结果没问题。这里则要使用另一种方法,如果链表是存在环的,那么在环的入口点继续遍历,将可能反复地遍历到这个环入口点,所以这里就可以使用两个变量来记录节点,让一个以步长1遍历,另一个以步长2遍历,显然步长2的遍历方式将会比步长1的快,若链表存在环,步长2的遍历方式将会在某时刻与步长1的遍历方式相遇。具体代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *one = head;
struct ListNode *two = head;
while (one != NULL && two != NULL && two->next != NULL) {
one = one->next;
two = two->next->next;
if (one == two) {
return true;
}
}
return false;
}