题目
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路
这道题不让用额外的空间,所以很简单,每遍历一个节点,就把它的next指向它本身,也就表明这个节点已经被遍历过了。如果遍历到某个节点,它的next是一个指向自身的节点,即它的next已经被遍历过了,则表明形成了环。
代码
/**
* 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 *next = head->next;
ListNode *pre = head;
while (next->next != NULL) {
if (next->next->next == next->next) {
return true;
}
pre = next;
next = next->next;
pre->next = pre;
}
return false;
}
};