[leetcode]141. Linked List Cycle
Analysis
新的一周开始啦~—— [坚持吖~]
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断一个链表是否有环,不要使用格外的数组来实现。
关于如何判断链表是否有环的博客: https://blog.csdn.net/cyuyanenen/article/details/51712420
Implement
方法一:
/**
* 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) {
if(head == NULL)
return false;
ListNode *slow = head->next;
if(slow == NULL)
return false;
ListNode *fast = slow->next;
while(fast != NULL && slow != NULL){
if(slow == fast)
return true;
slow = slow->next;
fast = fast->next;
if(fast != NULL)
fast = fast->next;
}
return false;
}
};
方法二:
/**
* 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) {
if(head == NULL)
return false;
ListNode *slow = head->next;
if(slow == NULL)
return false;
ListNode *fast = slow->next;
while(fast != NULL && slow != NULL){
if(slow == fast)
return true;
slow = slow->next;
fast = fast->next;
if(fast != NULL)
fast = fast->next;
}
return false;
}
};