问题:判断链表是否有环。
分析:利用快慢指针slow,fast
slow指针每次走一步,fast指针每次走两步,倘若存在环,则slow和fast必定在某一时刻相遇。
由于fast指针走的比slow快所以循环的时候只需要判断fast和fast->next不为空,判断fast->next是因为防止出现fast->NULL->next这种情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
/** *
Definition for singly-linked list. *
struct ListNode { *
int val; *
ListNode *next; *
ListNode(int x) : val(x), next(NULL) {} *
}; */ class Solution
{ public : bool hasCycle(ListNode
*head) { ListNode
*fast,*slow; if (head==NULL) return false ; slow=head; fast=head->next; while (fast!=NULL
&& fast->next!=NULL) { if (slow==fast) return true ; slow=slow->next; fast=fast->next->next; } return false ; } }; |