标签:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Linked List Two Pointers
/** * 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) return false; ListNode* slow = head->next; ListNode* fast = NULL; if(slow) fast = slow->next; while(fast && slow) { if(fast == slow) return true; if(fast->next && fast->next->next) fast = fast->next->next; else //reach the end return false; slow = slow->next; } return false; } };
标签:
原文地址:http://www.cnblogs.com/diegodu/p/4595685.html