/**
* 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 * dummy = new ListNode(-1);
dummy->next = head;
ListNode * p = dummy;
ListNode * q = dummy;
p = p->next;
q = q->next;
q = q->next;
while(p != NULL && q != NULL && q->next != NULL) {
if(p == q) {
return true;
}
p = p->next;
q = q->next;
q= q->next;
}
return false;
}
};
4/06/2014
Leetcode -- Linked List Cycle
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment