141. Linked List Cycle
Java example:
/**
* 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) {
if(head == null) return false;
ListNode slow = head, fast = head.next;
while(fast != null && fast.next != null){
if(fast == slow) return true;
fast = fast.next.next;
slow = slow.next;
}
return false;
}
}Python example:
Last updated
Was this helpful?