https://oj.leetcode.com/problems/linked-list-cycle/
Given a linked list, determine if it has a cycle in it.
Follow up:
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) {}
* };
*
* ex: 1->2->1, 1->2->NULL, 1->NULL, 1->2->3->4->2
*/
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;
}
};
'풀어본 Algorithm 문제 정리' 카테고리의 다른 글
[OJ.leetcode] Validate Binary Search Tree (0) | 2014.06.29 |
---|---|
[OJ.leetcode] Convert Sorted Array to Binary Search Tree (0) | 2014.06.29 |
[OJ.leetcode] Search Insert Position (0) | 2014.06.29 |
[OJ.leetcode] Valid Palindrome (0) | 2014.06.29 |
[OJ.leetcode] Evaluate Reverse Polish Notation (0) | 2014.06.29 |