Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
/*开始需要判断head是否为NULL,否则下面while循环条件就是报错了
runtime error: member access within null pointer of
type 'struct ListNode' [solution.c]
另外这里的双指针都指向head,快指针指向head->next,则还需检验
head->next是否为空*/
if(head == NULL)
return false;
struct ListNode *slow = head, *fast = head;
int ret = 0;
while(fast->next != NULL && fast->next->next != NULL ) {/*这里只用检验快指针,因为如果无环,快指针先到达NULL,另外
要检查下面相邻的两个,如果无环,快指针最后可能指向NULL的前一
或倒数第二个,如果只检查一个的话会报错runtime error:
member access within null pointer of type
'struct ListNode' [solution.c]*/
slow = slow->next;
fast = fast->next->next;
if(slow == fast){
ret = 1;
break;
}
}
if(ret == 1)
return true;
return false;
}
开始做这个题一直在while循环那里报错,总以为自己没问题,没想到啊!!!最后看到错误案例是无环时,于是分析了接近NULL的情况,总算分析出来了