## Question >[Leetcode 141. Linked List Cycle](https://leetcode.com/problems/linked-list-cycle) <br> :::info :::spoiler *Optimal Space & Time Complexity* <br> ``` - Time complexity: O() - Space complexity: O() ``` ::: <br> ## Thoughts & Solutions ### YC :::spoiler Code ```javascript= /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {boolean} */ var hasCycle = function(head) { let fast = head; while(fast && fast.next){ head = head.next; fast = fast.next.next; if(head === fast) return true; } return false; }; ``` ::: <hr/> ### Sol :::spoiler Code ```javascript= ``` ::: <hr/> ### 東 :::spoiler Code ```javascript= var hasCycle = function(head) { let slow = head; let fast = head; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; if (slow === fast) { return true; } } return false; }; ``` ::: <hr/> ### Jessie :::spoiler Code ```javascript= /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {boolean} */ var hasCycle = function (head) { let visitedList = []; while (head !== null) { visitedList.push(head); head = head.next; if (visitedList.includes(head)) return true; } return false; }; ``` ::: <hr/> ### 皮皮 :::spoiler Code ```python= class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False ``` ::: <br> ## Live Coding :::spoiler (name) ``` // write your code here ``` :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up