Skip to content

Instantly share code, notes, and snippets.

@yitonghe00
Last active November 1, 2019 03:29
Show Gist options
  • Save yitonghe00/4ad745b36e01bd159d83fb8a518867a6 to your computer and use it in GitHub Desktop.
Save yitonghe00/4ad745b36e01bd159d83fb8a518867a6 to your computer and use it in GitHub Desktop.
141. Linked List Cycle (https://leetcode.com/problems/linked-list-cycle/): Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
// Two pointer solution: slow/fast pointers
// Time: O(n), 0ms
// Space: O(1), 36.9mb
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) return true;
}
return false;
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment