Blogs   

Convert Binary Number in a Linked List to Integer

Published on 17 Jul 2025  ·  Written by Aditya Mayukh Som

Problem Link

This solution does not modify the original list, this temporarily reverses the list to move the head to the LSB of the binary representation and then while reading the number from LSB to MSB, this again reverses the linked list to it's original state.

class Solution:
    def getDecimalValue(self, head: Optional[ListNode]) -> int:
        if head is None:
            raise ValueError('linked list must contain one node')

        p, c = None, head

        # reverse to put the head of the LL to its LSB
        while c is not None:
            f = c.next
            c.next = p
            p = c
            c = f

        # after reversal, p contains the head of the LL, put that in c and make p as None
        c = p
        p = None

        # initial power of 2 is zero and number is zero
        num, e = 0, 0

        # while computing the number, again reset the LL to its original state
        while c is not None:
            num += c.val << e
            e += 1

            f = c.next
            c.next = p
            p = c
            c = f

        return num
Written by Aditya Mayukh Som.