Skip to content

Commit

Permalink
Create 142.Linked-List-Cycle-II.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
seungdols authored Mar 19, 2022
1 parent e1947b6 commit 2fe3e2c
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions algorithm/142.Linked-List-Cycle-II.kt
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
}
}

0 comments on commit 2fe3e2c

Please sign in to comment.