Python Program To Find Decimal Equivalent Of Binary Linked List
Last Updated :
22 Jun, 2022
Given a singly linked list of 0s and 1s find its decimal equivalent.
Input: 0->0->0->1->1->0->0->1->0
Output: 50
Input: 1->0->0
Output: 4
The decimal value of an empty linked list is considered as 0.
Initialize the result as 0. Traverse the linked list and for each node, multiply the result by 2 and add the node’s data to it.
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def decimalValue( self , head):
res = 0
while head:
res = (res << 1 ) + head.data
head = head. next
return res
if __name__ = = '__main__' :
llist = LinkedList()
llist.head = Node( 1 )
llist.head. next = Node( 0 )
llist.head. next . next = Node( 1 )
llist.head. next . next . next = Node( 1 )
print ( "Decimal Value is {}" . format (
llist.decimalValue(llist.head)))
|
Output :
Decimal value is 11
Time Complexity: O(n) where n is the number of nodes in the given linked list.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Please refer complete article on Decimal Equivalent of Binary Linked List for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...