[LeetCode] 206. Reverse Linked List(Kotlin)

0

LeetCode

목록 보기
16/58
post-thumbnail
post-custom-banner

[LeetCode] 206. Reverse Linked List(Kotlin)

풀이

  • iterative solution
/**
 * 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

        //linked list의 ListNode 순서대로 배열에 담기
        var listNodeArray = arrayOf<ListNode>(head)
        var cur = head!!
        while(cur.next != null){
            listNodeArray += cur.next
            cur = cur.next
        }

        //linked list의 ListNode 순서 뒤집기
        val tail = listNodeArray.last()
        for(i in listNodeArray.size-1 downTo 1){
            var child = listNodeArray[i]
            var parent = listNodeArray[i-1]
            child.next = parent
        }
        head.next = null //Cycle 삭제하기
        
        return tail
    }
}
profile
Be able to be vulnerable, in search of truth
post-custom-banner

0개의 댓글