Java 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->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.
Java
class GFG{
static class Node
{
boolean data;
Node next;
};
static int decimalValue(Node head)
{
int res = 0 ;
while (head != null )
{
res = (res << 1 ) + (head.data? 1 : 0 );
head = head.next;
}
return res;
}
static Node newNode( int data)
{
Node temp = new Node();
temp.data = (data == 1 ?
true : false );
temp.next = null ;
return temp;
}
public static void main(String args[])
{
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));
}
}
|
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!
Last Updated :
22 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...