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.
1public class ListNode {
2 public int val;
3 public ListNode next;
4 public ListNode(int x) { val = x; }
5}
6
7public class Solution {
8 public int GetDecimalValue(ListNode head) {
9 int len = 0, result = 0;
10 ListNode current = head;
11 while (current != null) {
12 len++;
13 current = current.next;
14 }
15 current = head;
16 while (current != null) {
17 result += current.val * (int)Math.Pow(2, --len);
18 current = current.next;
19 }
20 return result;
21 }
22}
For this C# method, we first determine the list's length for power calculations; each node's value progressively contributes to the final integer through multiplication with declining exponents of two.