Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active January 2, 2016 16:19
Show Gist options
  • Save junjiah/8329765 to your computer and use it in GitHub Desktop.
Save junjiah/8329765 to your computer and use it in GitHub Desktop.
solved "Linked List Cycle" I and II on LeetCode (the algorithm of fast runner and slow runner is awesome!! and the solution to the second is even more mind-blowing :) http://oj.leetcode.com/problems/linked-list-cycle/ *and* http://oj.leetcode.com/problems/linked-list-cycle-ii/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// GREAT algorithm! inspired by that discussion forum.
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast = head,
*slow = head;
do {
if (fast == NULL || fast->next == NULL)
return 0;
else {
fast = fast->next->next;
slow = slow->next;
}
} while (fast != slow);
return 1;
}
};
// Previous prob's variation
// check my blog
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast = head,
*slow = head;
do {
if (fast == NULL || fast->next == NULL)
return NULL;
else {
fast = fast->next->next;
slow = slow->next;
}
} while (fast != slow);
slow = head;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment