141. Linked List Cycle
2018-06-28 本文已影响0人
SilentDawn
Problem
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static int var = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL)
return false;
ListNode* fast = head;
ListNode* slow = head;
while(fast->next!=NULL && fast->next->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(slow==fast)
return true;
}
return false;
}
};