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
# Python3 program to find decimal value # of binary linked list # Node Class class Node:
# Function to initialise the
# node object
def __init__( self , data):
# Assign data
self .data = data
# Initialize next as null
self . next = None
# Linked List class contains # a Node object class LinkedList:
# Function to initialize head
def __init__( self ):
self .head = None
# Returns decimal value of binary
# linked list
def decimalValue( self , head):
# Initialized result
res = 0
# Traverse linked list
while head:
# Multiply result by 2 and
# add head's data
res = (res << 1 ) + head.data
# Move Next
head = head. next
return res
# Driver code if __name__ = = '__main__' :
# Start with the empty list
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)))
# This code is contributed by Mohit Jangra |
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!