题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

/**
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
object Solution {
    /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    *
    * 
        * @param head1 ListNode类 
        * @param head2 ListNode类 
        * @return ListNode类
    */
    fun addInList(head1: ListNode?,head2: ListNode?): ListNode?  {
        // write code here
        var rPoint1 = reverseList(head1)
        var rPoint2 = reverseList(head2)
        val mHead = ListNode(-1)
        var resultPoint: ListNode? = mHead
        var apend = 0
        while (true) {
            var num1 = 0
            var num2 = 0
            if (rPoint1 == null) {
                if (rPoint2 == null) {
                    break
                }
                num2 = rPoint2.`val`
            } else if (rPoint2 == null) {
                num1 = rPoint1.`val`
            } else {
                num1 = rPoint1.`val`
                num2 = rPoint2.`val`
            }
            val sum = num1 + num2 + apend
            val r = ListNode(sum % 10)
            apend = sum / 10
            resultPoint?.next = r
            resultPoint = resultPoint?.next
            rPoint1 = rPoint1?.next
            rPoint2 = rPoint2?.next
        }
        if (apend == 1) {
            val r = ListNode(1)
            resultPoint?.next = r
        }
        return reverseList(mHead.next)
    }

    private fun reverseList(head: ListNode?): ListNode?  {
        var current = head ?: return null
        var next = head?.next
        current.next = null
        while (next != null) {
            val last = current
            current = next
            next = current.next
            current.next = last
        }
        return current
    }
}



全部评论

相关推荐

hso_:哈哈哈哈哈哈我没offer一样在同一道题开喷了
投递深圳同为数码等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务