141. Linked List Cycle
my code that destroy the list
/**
* 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) {
ListNode *curr = head;
if (head == NULL)return false;
while(curr->next) {
ListNode *tmp = curr->next;
if (tmp == head)return true;
curr->next = head;
curr = tmp;
}
return false;
}
};
tortoise and hare algorithm
/**
* 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;
//pay attention not forget to see ifnull head->next
ListNode *tortoise = head;
ListNode *hare = head;
while(hare->next && hare->next->next) {
//should first ensure that hare->next is not NULL then hare->next has next
tortoise = tortoise->next;
hare = hare->next->next;
if (tortoise == hare)return true;
}
return false;
}
};