Skip to content

Commit

Permalink
Kotlin: 206. Reverse Linked List
Browse files Browse the repository at this point in the history
  • Loading branch information
MaratKhakim committed Aug 23, 2022
1 parent d755dad commit cff97dd
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions kotlin/206-Reverse-Linked-List.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* 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 reverseList(head: ListNode?): ListNode? {
if (head == null)
return head

var prev: ListNode? = null
var curr = head

while (curr != null) {
val next = curr.next
curr.next = prev
prev = curr
curr = next
}

return prev
}

fun reverseListRecursive(head: ListNode?): ListNode? {
if (head == null || head.next == null)
return head

val newHead = reverseList(head.next)
head.next.next = head
head.next = null

return newHead
}
}

0 comments on commit cff97dd

Please sign in to comment.