Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目解析:
判断是否有环,只需要快慢指针即可。注意考虑程序的健壮性。
class Solution { public: bool hasCycle(ListNode *head) { if(head == NULL || head->next == NULL) return false; ListNode *p,*q; p = head; q = head->next; while(q->next && p!=q){ p = p->next; if(q->next->next == NULL ) return false; q = q->next->next; } if(p == q) return true; else return false; } };