Double a Number Represented as a Linked List

medium linked list math

Problem

A non-negative integer is stored as a linked list with the most significant digit at the head (one digit per node, no leading zeros except the number 0 itself). Multiply that number by two and return the result as a linked list in the same most-significant-first order.

Inputhead = 1→8→9
Output3→7→8
The list represents 189, and 189 × 2 = 378, so the answer is 3→7→8.

def double_it(head):
    if head.val >= 5:
        head = ListNode(0, head)
    node = head
    while node:
        node.val = (node.val * 2) % 10
        if node.next and node.next.val >= 5:
            node.val += 1
        node = node.next
    return head
function doubleIt(head) {
  if (head.val >= 5) {
    head = { val: 0, next: head };
  }
  let node = head;
  while (node) {
    node.val = (node.val * 2) % 10;
    if (node.next && node.next.val >= 5) {
      node.val += 1;
    }
    node = node.next;
  }
  return head;
}
class Solution {
    public ListNode doubleIt(ListNode head) {
        if (head.val >= 5) {
            head = new ListNode(0, head);
        }
        ListNode node = head;
        while (node != null) {
            node.val = (node.val * 2) % 10;
            if (node.next != null && node.next.val >= 5) {
                node.val += 1;
            }
            node = node.next;
        }
        return head;
    }
}
ListNode* doubleIt(ListNode* head) {
    if (head->val >= 5) {
        head = new ListNode(0, head);
    }
    ListNode* node = head;
    while (node != nullptr) {
        node->val = (node->val * 2) % 10;
        if (node->next != nullptr && node->next->val >= 5) {
            node->val += 1;
        }
        node = node->next;
    }
    return head;
}
Time: O(n) Space: O(1)