题解 | #链表相加(二)#
链表相加(二)
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 } }