Program to convert Linked list representing binary number to decimal integer in Python

Suppose we have a singly linked list. the linked list is representing a binary number with most significant digits first, we have to return it as decimal number.

So, if the input is like [1,0,1,1,0], then the output will be 22

To solve this, we will follow these steps −

  • l := a new list
  • while node is not null, do
    • insert value of node at the end of l
    • node:= next of node
  • k := 0, v:= 0
  • for i in range size of l - 1 to 0, decrease by 1, do
    • if l[i] is same as 1, then
      • v := v + 2^k
    • k := k + 1
  • return v

Let us see the following implementation to get better understanding −


 Live Demo

class ListNode:
   def __init__(self, data, next = None):
      self.val = data = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
         ptr = = ListNode(element)
   return head
class Solution:
   def solve(self, node):
      l = []
      while node:
         k = 0
         for i in range(len(l)-1,-1,-1):
            if (l[i]==1):
            v += (2**k)
return v
ob = Solution()
head = make_list([1,0,1,1,0])