📜  查找二进制链表的十进制等价物的Python程序

📅  最后修改于: 2022-05-13 01:56:56.578000             🧑  作者: Mango

查找二进制链表的十进制等价物的Python程序

给定一个 0 和 1 的单链表,找到它的十进制等价物。

Input: 0->0->0->1->1->0->0->1->0
Output: 50   

Input: 1->0->0
Output: 4

空链表的十进制值被认为是 0。

将结果初始化为 0。遍历链表,对于每个节点,将结果乘以 2 并将节点的数据添加到其中。

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


输出 :

Decimal value is 11

有关详细信息,请参阅有关二进制链表的十进制等价的完整文章!