【LeetCode】141. 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?

代码

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* p = head;
        if(p==0) return false;
        ListNode* q = head->next;
        while(p&&q) {
        	if(p==q) return true;
        	p = p->next;
			if(q->next) {
				q = q->next->next;
			} else {
				return false;
			}	
        }
        return false;
    }
};