# 141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Can you solve it without using extra space?

Thoughts:

1. slow and fast pointer
2. Change the value of the node (mark)

Code 1

``````/**
* 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) return false;
ListNode* slow = head, *fast = head;
while(fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
}

return false;
}
};
``````

Code 1 Using Exception (Python)

``````# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: bool
"""
try:
while slow is not fast:
slow = slow.next
fast = fast.next.next
return True;

except:
return False;
``````

Code 2 (Java)

``````/**
* Definition for singly-linked list.
* class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {