141 - Linked List Cycle
Written on October 21, 2015
Tweet
Given a linked list, determine if it has a cycle in it.
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null) return false;
ListNode curr = head;
ListNode runner = head;
while(runner != null && runner.next != null) {
head = head.next;
runner = runner.next.next;
if (runner == head) return true;
//if there is cycle, this can end the while loop
//if there is no cycle, the loop will ends automatically
//since runner will gets to null
}
return false;
}
}
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
/**
* 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* slow = head;
ListNode* fast = head;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
return true;
}
}
return false;
}
};