File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed
kotlin/Fast and Slow Pointers Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Definition of ListNode:
3
+ data class ListNode(var value: Int, var next: ListNode? = null)
4
+ */
5
+
6
+ fun linkedListLoop (head : ListNode ? ): Boolean {
7
+ var slow = head
8
+ var fast = head
9
+ // Check both 'fast' and 'fast.next' to avoid null pointer
10
+ // exceptions when we perform 'fast.next' and 'fast.next.next'.
11
+ while (fast != null && fast.next != null ) {
12
+ slow = slow!! .next
13
+ fast = fast.next!! .next
14
+ if (fast == slow) {
15
+ return true
16
+ }
17
+ }
18
+ return false
19
+ }
Original file line number Diff line number Diff line change
1
+ /*
2
+ Definition of ListNode:
3
+ data class ListNode(var value: Int, var next: ListNode? = null)
4
+ */
5
+
6
+ fun linkedListLoopNaive (head : ListNode ? ): Boolean {
7
+ val visited = mutableSetOf<ListNode >()
8
+ var curr = head
9
+ while (curr != null ) {
10
+ // Cycle detected if the current node has already been visited.
11
+ if (visited.contains(curr)) {
12
+ return true
13
+ }
14
+ visited.add(curr)
15
+ curr = curr.next
16
+ }
17
+ return false
18
+ }
You can’t perform that action at this time.
0 commit comments