Skip to content

Instantly share code, notes, and snippets.

@walkingtospace
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkingtospace/cf057d4f0fd9e565a82f to your computer and use it in GitHub Desktop.
Save walkingtospace/cf057d4f0fd9e565a82f to your computer and use it in GitHub Desktop.
주어진 linkedlist에서 cycle 찾는 문제
Q. Given a linked list, determine if it has a cycle in it. Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*
* test case: 1->2->1, 1->2->NULL, 1->NULL, 1->2->3->4->2 ...
* solution : slow, fast runner를 이용하여 fast, slow runner가 한번이라도 만나면 return false.
* Time Complexity : O(2n)
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fastRunner = head;
ListNode* slowRunner = head;
while(fastRunner != NULL && fastRunner->next != NULL) {
fastRunner = fastRunner->next;
if(fastRunner == slowRunner) return true;
fastRunner = fastRunner->next;
slowRunner = slowRunner->next;
if(fastRunner == slowRunner) return true;
}//end while
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment