问题:判断链表是否有环。
分析:利用快慢指针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; }}; |
链表环检测
本文介绍了一种使用快慢指针来判断链表中是否存在环的方法。通过定义两个指针,一个快指针每次移动两步,一个慢指针每次移动一步,如果链表中有环,这两个指针最终会相遇。
373

被折叠的 条评论
为什么被折叠?



