Plus One Linked List

medium linked list

Problem

Given a non-empty linked list representing a non-negative integer, add one to it (most significant digit first).

Input[1, 2, 3]
Output[1, 2, 4]
No carry needed — last node 3 → 4.

def plus_one(head):
    not_nine = sentinel = type(head)(0)
    sentinel.next = head
    cur = head
    while cur:
        if cur.val != 9: not_nine = cur
        cur = cur.next
    not_nine.val += 1
    n = not_nine.next
    while n:
        n.val = 0
        n = n.next
    return head if sentinel.next is head and sentinel.val == 0 else sentinel
function plusOne(head) {
  const sentinel = { val: 0, next: head };
  let notNine = sentinel, cur = head;
  while (cur) {
    if (cur.val !== 9) notNine = cur;
    cur = cur.next;
  }
  notNine.val += 1;
  let n = notNine.next;
  while (n) { n.val = 0; n = n.next; }
  return sentinel.val === 0 ? sentinel.next : sentinel;
}
class Solution {
    public ListNode plusOne(ListNode head) {
        ListNode sentinel = new ListNode(0); sentinel.next = head;
        ListNode notNine = sentinel, cur = head;
        while (cur != null) {
            if (cur.val != 9) notNine = cur;
            cur = cur.next;
        }
        notNine.val++;
        ListNode n = notNine.next;
        while (n != null) { n.val = 0; n = n.next; }
        return sentinel.val == 0 ? sentinel.next : sentinel;
    }
}
ListNode* plusOne(ListNode* head) {
    ListNode sentinel(0); sentinel.next = head;
    ListNode* notNine = &sentinel; ListNode* cur = head;
    while (cur) { if (cur->val != 9) notNine = cur; cur = cur->next; }
    notNine->val++;
    for (ListNode* n = notNine->next; n; n = n->next) n->val = 0;
    return sentinel.val == 0 ? sentinel.next : new ListNode(1, sentinel.next);
}
Time: O(n) Space: O(1)