Skip to main content

2816. Double a Number Represented as a Linked List

Link

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:

current = head

prev = None

# make it become double linked list
while current != None:

current.prev, prev = prev , current
current = current.next

reverse = head

while reverse.next != None:
reverse = reverse.next


extra = 0

while reverse:
val = reverse.val * 2 + extra

if val >= 10:
extra = 1
val = val % 10
else:
extra = 0

reverse.val = val
reverse = reverse.prev

if extra:
new = TreeNode(1)
head, head.next = new, head

return head