Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Decimal Equivalent of Binary Linked List
Next article icon

Decimal Equivalent of Binary Linked List

Last Updated : 28 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

Recommended Practice
Decimal Equivalent of Binary Linked List
Try It!

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.

C++
// C++ Program to find decimal value of  // binary linked list  #include <bits/stdc++.h> 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 program to test above function*/ 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 
C
// C Program to find decimal value of // binary linked list #include<iostream> using namespace std;  /* Link list Node */ struct Node {     bool data;     struct Node* next; };  /* Returns decimal value of binary linked list */ int decimalValue(struct 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) {     struct Node *temp = new Node;     temp->data = data;     temp->next = NULL;     return temp; }  /* Driver program to test above function*/ int main() {     /* Start with the empty list */     struct 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; } 
Java
// Java Program to find decimal value of  // binary linked list  class GFG {      // Link list Node / static class Node  {      boolean data;      Node next;  };   // Returns decimal value of binary linked list / static 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?1:0);           // Move next          head = head.next;      }      return res;  }   // Utility function to create a new node.  static Node newNode(int data)  {      Node temp = new Node();      temp.data = (data==1? true:false);      temp.next = null;      return temp;  }   // Driver code/ public static void main(String args[]) {      // Start with the empty list /     Node head = newNode(1);      head.next = newNode(0);      head.next.next = newNode(1);      head.next.next.next = newNode(1);       System.out.print( "Decimal value is "+decimalValue(head));  } }  // This code is contributed by Arnab Kundu 
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 
C#
// C# Program to find decimal value of  // binary linked list  using System;  class GFG {      // Link list Node / public class Node  {      public Boolean data;      public Node next;  };   // Returns decimal value of binary linked list static 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 ? 1 : 0);           // Move next          head = head.next;      }      return res;  }   // Utility function to create a new node.  static Node newNode(int data)  {      Node temp = new Node();      temp.data = (data == 1 ? true : false);      temp.next = null;      return temp;  }   // Driver code public static void Main(String []args) {      // Start with the empty list      Node head = newNode(1);      head.next = newNode(0);      head.next.next = newNode(1);      head.next.next.next = newNode(1);       Console.WriteLine("Decimal value is " +                         decimalValue(head));  } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>  // Javascript Program to find decimal value of  // binary linked list      // Link list Node /      class Node {          constructor(){          this.data = true;          this.next = null;     }     }      // Returns decimal value of binary linked list /     function decimalValue(head) {         // Initialized result         var res = 0;          // Traverse linked list         while (head != null) {             // Multiply result by 2 and add             // head's data             res = (res << 1) + (head.data ? 1 : 0);              // Move next             head = head.next;         }         return res;     }      // Utility function to create a new node.     function newNode(data) { var temp = new Node();         temp.data = (data == 1 ? true : false);         temp.next = null;         return temp;     }      // Driver code/              // Start with the empty list / var head = newNode(1);         head.next = newNode(0);         head.next.next = newNode(1);         head.next.next.next = newNode(1);          document.write("Decimal value is "          + decimalValue(head));  // This code contributed by aashish1995   </script> 

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.

Another Approach(by reversing the Linked List):
Follow the below steps to solve the given problem
1) First reverse the given linked list.
2) Initialize a ans variable to store ans and pos variable to keep track of position of node in linked list.
3) Perform the operation ans = ans + (rhead.data*(2**pos))%MOD)
4) perform ans = ans%MOD

Below is the implementation of above approach:

C++
#include<bits/stdc++.h> using namespace std; // C++ Program to find decimal value // of binary linked list  // node structure struct Node{     int data;     Node* next;     Node(int data){         this->data = data;         this->next = NULL;     } };  long long unsigned int power(int num,int count){    if(count ==0) return 1;    if(count%2==0)        return (power(num,count/2)%1000000007)*(power(num,count/2)%1000000007);    else        return num*(power(num,count/2)%1000000007)*(power(num,count/2)%1000000007);; }  Node* reverse(Node* head){     if(head == NULL || head->next == NULL) return head;          Node* curr = head;     Node* prev = NULL;     Node* nxt = head->next;     while(nxt != NULL){         curr->next = prev;         prev = curr;         curr = nxt;         nxt = nxt->next;     }     curr->next = prev;     return curr; }  int decimalValue(Node* head){     int MOD = 1000000007;     Node* rhead = reverse(head);          int ans = 0;     int pos = 0;     while(rhead != NULL){         ans = (ans%MOD + ((rhead->data)*power(2,pos)) % MOD) % MOD;         rhead = rhead->next;         pos++;     }     return ans; }  int main(){     Node* head = new Node(1);     head->next = new Node(0);     head->next->next = new Node(1);     head->next->next->next = new Node(1);          cout<<"Decimal Value is : "<<decimalValue(head); } 
Java
// Java implementation to find non-leaf // count of a given Binary tree import java.util.*;  // class to represent the tree node class Node{     public int data;     public Node next;     public Node(int item){         data = item;         next = null;     } }  public class LinkedList{     static int power(int num, int count){         if(count ==0) return 1;         if(count % 2 ==0)             return (power(num,count/2)%1000000007)*(power(num,count/2)%1000000007);         else             return num*(power(num,count/2)%1000000007)*(power(num,count/2)%1000000007);     }          static Node reverse(Node head){         if(head == null || head.next == null) return head;                  Node curr = head;         Node prev = null;         Node nxt = head.next;         while(nxt != null){             curr.next = prev;             prev = curr;             curr = nxt;             nxt = nxt.next;         }         curr.next = prev;         return curr;     }          static int decimalValue(Node head){         Node rhead = reverse(head);                  int ans = 0;         int pos = 0;         while(rhead != null){             ans = (ans % 1000000007 + ((rhead.data)*((int)power(2,pos))) % 1000000007) % 1000000007;             rhead = rhead.next;             pos++;         }         return ans;     }          // driver code to test above function     public static void main(String args[]){         Node head = new Node(1);         head.next = new Node(0);         head.next.next = new Node(1);         head.next.next.next = new Node(1);                  // function call         System.out.println("Decimal Value is : " + decimalValue(head));     } } 
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                   def reverse(head):     if(head == None or head.next == None):         return head     curr = head     prev = None     nxt = head.next     while(nxt):         curr.next = prev         prev = curr         curr = nxt         nxt = nxt.next     curr.next = prev     return curr   def decimalValue(head):     MOD=10**9+7     rhead = reverse(head)      ans = 0     pos = 0     while rhead:         ans = (ans % MOD+(rhead.data*(2**pos)) % MOD) % MOD         rhead = rhead.next         pos += 1     return ans       head = Node(1) head.next = Node(0) head.next.next = Node(1) head.next.next.next = Node(1)  print("Decimal Value is :", end =" ") print(decimalValue(head))  # THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002) 
C#
using System;  // C# Program to find decimal value // of binary linked list class GFG{   public class Node{     public int data;     public Node next;     public Node(int data){       this.data = data;       this.next = null;     }   }    static int power(int num, int count){     if(count == 0) return 1;     if(count%2==0)       return (power(num,count/2)%1000000007)*(power(num,count/2)%1000000007);     else       return num*(power(num,count/2)%1000000007)*(power(num,count/2)%1000000007);   }    static Node reverse(Node head){     if(head == null || head.next == null) return head;     Node curr = head;     Node prev = null;     Node nxt = head.next;     while(nxt != null){       curr.next = prev;       prev = curr;       curr = nxt;       nxt = nxt.next;     }     curr.next = prev;     return curr;   }    static int decimalValue(Node head){     int MOD = 1000000007;     Node rhead = reverse(head);      int ans = 0;     int pos = 0;     while(rhead != null){       ans = (ans%MOD + ((rhead.data)*power(2,pos)) % MOD) % MOD;       rhead = rhead.next;       pos++;     }     return ans;   }    public static void Main(){     Node head = new Node(1);     head.next =  new Node(0);     head.next.next = new Node(1);     head.next.next.next = new Node(1);     Console.WriteLine("Decimal Value is : " + decimalValue(head));   } } 
JavaScript
// JavaScript program to find the decimal value // of binary linked list // node class class Node{     constructor(data){         this.data = data;         this.left = null;         this.right = null;     } }  function reverse(head){     if(head == null || head.next == null) return head;          let curr = head;     let prev = null;     let nxt = head.next;     while(nxt != null){         curr.next = prev;         prev = curr;         curr = nxt;         nxt = nxt.next;     }     curr.next = prev;     return curr; }  function decimalValue(head){     let MOD = 1000000007;     let rhead = reverse(head);          let ans = 0;     let pos = 0;     while(rhead != null){         ans = (ans % MOD+(rhead.data*(2**pos)) % MOD) % MOD;         rhead = rhead.next;         pos += 1;     }     return ans; }  // driver program to test above function let head = new Node(1); head.next = new Node(0); head.next.next = new Node(1); head.next.next.next= new Node(1);  console.log("Decimal Value is : " + decimalValue(head)); 

Output
Decimal Value is : 11 

Time Complexity: O(N) where N is the number of nodes in linked list.
Auxiliary Space: O(1)

 


Next Article
Decimal Equivalent of Binary Linked List

K

kartik
Improve
Article Tags :
  • Linked List
  • DSA
  • Juniper Networks
Practice Tags :
  • Juniper Networks
  • Linked List

Similar Reads

    Javascript Program To Find Decimal Equivalent Of Binary Linked List
    Given a singly linked list of 0s and 1s find its decimal equivalent.Input: 0->0->0->1->1->0->0->1->0Output: 50 Input: 1->0->0Output: 4The decimal value of an empty linked list is considered as 0.Initialize the result as 0. Traverse the linked list and for each node, mul
    3 min read
    Memory efficient doubly linked list
    We need to implement a doubly linked list with the use of a single pointer in each node. For that we are given a stream of data of size n for the linked list, your task is to make the function insert() and getList(). The insert() function pushes (or inserts at the beginning) the given data in the li
    9 min read
    Split a Circular Linked List into two halves
    Given a Circular linked list. The task is split into two Circular Linked lists. If there are an odd number of nodes in the given circular linked list then out of the resulting two halved lists, the first list should have one node more than the second list.Examples:Input: 10->4->9Output: 10-
    10 min read
    Bitonic point in the given linked list
    Given a linked list with distinct elements, the task is to find the bitonic point in the given linked list. If there is no such point then print -1. Examples: Input: 1 -> 2 -> 3 -> 4 -> 3 -> 2 -> 1 -> NULL Output: 4 1 -> 2 -> 3 -> 4 is strictly increasing. 4 -> 3 -
    7 min read
    Find Length of a Linked List (Iterative and Recursive)
    Given a Singly Linked List, the task is to find the Length of the Linked List.Examples:Input: LinkedList = 1->3->1->2->1Output: 5Explanation: The linked list has 5 nodes.Input: LinkedList = 2->4->1->9->5->3->6Output: 7 Explanation: The linked list has 7 nodes.Input: Lin
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences