📜  查找二进制链表的十进制等效项的 C++ 程序

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

查找二进制链表的十进制等效项的 C++ 程序

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

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

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

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

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

C++
// C++ Program to find decimal value 
// of binary linked list 
#include 
using namespace std;
  
// Link list Node 
class Node 
{ 
    public:
    bool data; 
    Node* next; 
}; 
  
/* Returns decimal value of binary 
   linked list */
int decimalValue(Node *head) 
{ 
    // Initialized result 
    int res = 0; 
  
    // Traverse linked list 
    while (head != NULL) 
    { 
        // Multiply result by 2 and 
        // add head's data 
        res = (res << 1) + head->data; 
  
        // Move next 
        head = head->next; 
    } 
    return res; 
} 
  
// Utility function to create a 
// new node. 
Node *newNode(bool data) 
{ 
    Node *temp = new Node; 
    temp->data = data; 
    temp->next = NULL; 
    return temp; 
} 
  
// Driver code
int main() 
{ 
    // Start with the empty list 
    Node* head = newNode(1); 
    head->next = newNode(0); 
    head->next->next = newNode(1); 
    head->next->next->next = newNode(1);
    cout << "Decimal value is " << 
             decimalValue(head); 
    return 0; 
} 
// This is code is contributed by rathbhupendra


输出 :

Decimal value is 11

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