问题重现:
- 给定一个链表,判断其中是否存在一个循环(尽量不使用额外空间)
分析思路:
1、暴力解法,即从第二个节点开始,每一个新的节点都与其前面的全部节点进行比较,判断是否有循环,时间复杂度为O(N^2),空间复杂度为O(N)
2、采用快慢指针的思想,即用两个指针分别遍历整个链表,慢指针每次前进1个节点,快指针每次前进2个节点,若两指针相遇,那么判断存在循环;否则不存在循环。时间复杂度为O(N),空间复杂度为O(1)
问题解决:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *fast = head, *slow = head;
while(fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
if(fast == slow) //if they equal, it has a cycle
return true;
}
return false; //while a pointer is NULL, it doesn't have a cycle
}