Java程序查找二进制链接列表的十进制等价物
给定一个 0 和 1 的单链表,找到它的十进制等价物。
Input: 0->0->0->1->1->0->0->1->0
Output: 50
Input: 1->0->0
Output: 4
空链表的十进制值被认为是 0。
将结果初始化为 0。遍历链表,对于每个节点,将结果乘以 2 并将节点的数据添加到其中。
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
输出 :
Decimal value is 11
有关详细信息,请参阅有关二进制链接列表的十进制等价的完整文章!