Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:思想很简单,定义快慢指针,看它们是否会相遇
在写法上需要注意一下while循环的条件。
下面是两种写法:
代码:
1、
/**
* 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 || head->next==NULL)
return false;
ListNode *slow = head;
ListNode *fast = head->next;
while(slow!=NULL && fast!=NULL){//注意循环条件,这样写循环体里不需要判断它俩是否为空,下一次跳出就可以了
if(slow==fast)
return true;
slow = slow->next;
fast = fast->next;
if(fast!=NULL)//这里需要加这样的判断条件避免出现对空指针取next发生段错误
fast = fast->next;
}
return false;
}
};
2、
/**
* 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 || head->next==NULL)
return false;
ListNode *slow = head;
ListNode *fast = head;//这里由于定义的时候二者都指向链表头,所以循环里只能先后移后判断是否相等
while(fast!=NULL && fast->next!=NULL){
//关于循环条件,由于用到了fast->next->next,所以需要保证fast->next不为空
//而判断fast->next不为空的前提需要保证fast不为空,否则判断fast->next的时候就会出错
slow = slow->next;//这里因为直接后移,所以循环条件就需要加一些判断,而不能简单地判断二者不为空
fast = fast->next->next;
if(slow==fast)
return true;
}
return false;
}
};