Skip to content

Commit c2408fb

Browse files
committed
solve
1 parent af17889 commit c2408fb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

linked-list-cycle/sonjh1217.swift

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* public var val: Int
5+
* public var next: ListNode?
6+
* public init(_ val: Int) {
7+
* self.val = val
8+
* self.next = nil
9+
* }
10+
* }
11+
*/
12+
13+
extension ListNode: Equatable {
14+
public static func == (lhs: ListNode, rhs: ListNode) -> Bool {
15+
return lhs === rhs
16+
}
17+
}
18+
19+
extension ListNode: Hashable {
20+
public func hash(into hasher: inout Hasher) {
21+
hasher.combine(ObjectIdentifier(self))
22+
}
23+
}
24+
25+
class Solution {
26+
// O(n) time / O(n) space
27+
func hasCycle(_ head: ListNode?) -> Bool {
28+
var visitedNodes = Set<ListNode>()
29+
var node = head
30+
31+
while node != nil {
32+
guard let currentNode = node else {
33+
return false
34+
}
35+
36+
if visitedNodes.contains(currentNode) {
37+
return true
38+
}
39+
40+
visitedNodes.insert(currentNode)
41+
node = currentNode.next
42+
}
43+
44+
return false
45+
}
46+
47+
// O(n) time / O(1) space
48+
func hasCycleFloyd(_ head: ListNode?) -> Bool {
49+
var slow = head
50+
var fast = head
51+
52+
while fast != nil && fast?.next != nil {
53+
slow = slow?.next
54+
fast = fast?.next?.next
55+
56+
if slow === fast {
57+
return true
58+
}
59+
}
60+
61+
return false
62+
}
63+
}

0 commit comments

Comments
 (0)