Question:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断一个链表是否为循环链表,只要有NULL出现就不是循环链表。
方法:设置两个指针,第一个指针从头开始走两步每次,第二个指针每次从头开始走一步;如果第一个指针追上了第二个指针这说明是循环链表;否则不是循环链表。
代码如下:
<span style="font-size:14px;">/**
* 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* pre = head->next->next;
ListNode* last = head;
if(pre == NULL)
return false;
else{
while(pre != last){
if(pre->next != NULL && pre->next->next != NULL){
pre = pre->next->next;
last = last->next;
}
else
return false;
}
return true;
}
}
};</span>