-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
/** | ||
* Example: | ||
* var li = ListNode(5) | ||
* var v = li.`val` | ||
* Definition for singly-linked list. | ||
* class ListNode(var `val`: Int) { | ||
* var next: ListNode? = null | ||
* } | ||
*/ | ||
|
||
class Solution { | ||
fun detectCycle(head: ListNode?): ListNode? { | ||
|
||
var first = head | ||
var second = head | ||
var cyclePos = head | ||
while(first != null && first.next != null) { | ||
first = first?.next?.next | ||
second = second?.next | ||
if (first == second) { | ||
while(second != cyclePos) { | ||
second = second?.next | ||
cyclePos = cyclePos?.next | ||
} | ||
return cyclePos | ||
} | ||
} | ||
|
||
return null | ||
} | ||
} |