Linked List Cycle(2014.2.7)

来源:互联网 发布:大学毕业证制作软件 编辑:程序博客网 时间:2024/05/18 15:53
/**
 * 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) {
        ListNode *p=head;
        ListNode *q=head;
        while(q!=NULL&&q->next!=NULL){
            p=p->next;
            q=q->next->next;
            if(p==q) return true;
        }
        return false;
    }
};
0 0