Leetcode-Solutions

My Leetcode Solutions.

View on GitHub

141. Linked List Cycle

Topics: Hash Table Linked List Two Pointers

Solution 1

Implementation

class Solution {
    fun hasCycle(head: ListNode?): Boolean {
        val nodeSet = mutableSetOf<ListNode>()
        var current = head

        while (current != null) {
            if (current in nodeSet) return true
            nodeSet.add(current)
            current = current.next
        }

        return false
    }
}

Solution 2

Implementation

class Solution {
    fun hasCycle(head: ListNode?): Boolean {
        var first = head
        var second = head

        while (first != null && first.next != null && second != null) {
            first = first.next.next
            second = second.next
            if (first == second) return true
        }

        return false
    }
}