Kotlin Leetcode - 206. Reverse Linked List
/**
* 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? {
}
}
解題思路
這一題考的是對 linked list 的處理
基本上透過一個 while 迴圈處理即可
Kotlin 參考解答
點擊展開解答
class Solution {
fun reverseList(head: ListNode?): ListNode? {
var reversed: ListNode? = null
var current = head
while (current != null) {
reversed = ListNode(current.`val`)
.apply { next = reversed }
current = current.next
}
return reversed
}
}
- 回到 leetcode 列表
- 回到 Grind 75 列表