LeetCode: Linked List Cycle Solution
Make used of duck typingApproach
Set the visited
state for each node, if revisit a visited node, then the list contains cycle
Implementation
1/**2 * Definition for singly-linked list.3 * function ListNode(val) {4 * this.val = val;5 * this.next = null;6 * }7 */89/**10 * @param {ListNode} head11 * @return {boolean}12 */13var hasCycle = function (head) {14 if (!head) {15 return false16 }17 if (head.visited) {18 return true19 }20 head.visited = true21 return hasCycle(head.next)22}
Comments
Loading comments...
Tags
leetcode
linked list
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.