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

PythonServer Side ProgrammingProgramming

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 −

Example

 Live Demo

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

Input

[1,0,1,1,0]

Output

22
raja
Published on 06-Oct-2020 06:10:53
Advertisements