Friday, March 18, 2016

LeetCode Q141: 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?


/**
* 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* p0 = head;
ListNode* p1 = head;
while(p1->next!=NULL&&p1->next->next!=NULL){
p0 = p0->next;
p1 = p1->next->next;
if(p0==p1)
return true;
}
return false;
}
};

No comments:

Post a Comment