This approach involves traversing the linked list and building the decimal value using bit manipulation. As the linked list is traversed, the current result is shifted left by one bit (equivalent to multiplying by 2), and the current node's value is added using the OR operation.
Time Complexity: O(n), where n is the number of nodes in the linked list.
Space Complexity: O(1), as we only use a constant amount of additional space.
1#include <stdlib.h>
2
3struct ListNode {
4 int val;
5 struct ListNode *next;
6};
7
8int getDecimalValue(struct ListNode* head) {
9 int result = 0;
10 while (head != NULL) {
11 result = (result << 1) | head->val;
12 head = head->next;
13 }
14 return result;
15}
The function getDecimalValue
traverses the linked list, updating the result
by left-shifting it by one bit and then OR-ing it with the current node's value. This operation effectively constructs the binary number bit by bit.
This approach involves traversing the linked list twice. First, to count the nodes (and hence determine the power of two to start with) and second to compute the decimal value by iterating through the list again, multiplying each binary digit by the appropriate power of two.
Time Complexity: O(n), where n is the number of nodes, but involves two passes.
Space Complexity: O(1), since it uses constant space plus a few variables.
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class Solution:
7 def getDecimalValue(self, head: ListNode) -> int:
8 length = 0
9 current = head
10 while current:
11 length += 1
12 current = current.next
13 result = 0
14 current = head
15 while current:
16 result += current.val * (2 ** (length - 1))
17 length -= 1
18 current = current.next
19 return result
The Python version operates similarly by first counting nodes to establish ordering with powers of two, and followed by accumulating the decimal value through a second, orderly pass.