Last active
November 1, 2019 03:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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