[LeetCode] 2095. Delete the Middle Node of a Linked List(Kotlin)

0

LeetCode

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

[LeetCode] 2095. Delete the Middle Node of a Linked List(Kotlin)

풀이

/**
 * 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 deleteMiddle(head: ListNode?): ListNode? {
        val size = getSize(head)
        if(size == 1) return null
        
        var index = 0
        var prev: ListNode? = null
        var cur: ListNode? = head
        while((index < (size/2)) && (cur != null)){
            prev = cur
            cur = cur.next
            index++
        }
        // when index == (size/2), delete cur node 
        prev!!.next = cur!!.next
        
        return head
    }

    private fun getSize(head: ListNode?): Int{
        if(head == null) return 0
        return 1 + getSize(head.next)
    }
}
profile
Be able to be vulnerable, in search of truth
post-custom-banner

0개의 댓글