Medium
You are given the head
of a non-empty linked list representing a non-negative integer without leading zeroes.
Return the head
of the linked list after doubling it.
Example 1:
Input: head = [1,8,9]
Output: [3,7,8]
Explanation: The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.
Example 2:
Input: head = [9,9,9]
Output: [1,9,9,8]
Explanation: The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998.
Constraints:
[1, 104]
0 <= Node.val <= 9
0
itself.import com_github_leetcode.ListNode
/*
* 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 doubleIt(head: ListNode?): ListNode? {
var temp1 = revList(head)
var list1: ListNode? = null
var current = list1
var carry = 0
while (temp1 != null) {
val `val` = temp1.`val` * 2
if (list1 == null) {
list1 = ListNode(`val` % 10 + carry)
current = list1
} else {
current!!.next = ListNode(`val` % 10 + carry)
current = current.next
}
carry = `val` / 10
temp1 = temp1.next
}
if (carry == 1) {
current!!.next = ListNode(carry)
}
return revList(list1)
}
private fun revList(head: ListNode?): ListNode? {
var prev: ListNode? = null
var nxt: ListNode?
var current = head
while (current != null) {
nxt = current.next
current.next = prev
prev = current
current = nxt
}
return prev
}
}