Problem Link : Binary Linked List Representation
Problem Statement:
The task is to create a linked list that represents the binary representation of a given non-negative integer N and print the linked list in a readable format.
Approach:
The key idea is to create a linked list that represents the binary form of a non-negative integer N.
-
Node Structure: We define a
Nodestruct with an integerdatato hold a bit (0 or 1) and a pointernextto link to the next node. -
Creating the Linked List:
-
If
Nis0, we create a node with data0as thehead. -
For
N > 0, we initialize theheadasnullptr. We repeatedly extract the last bit ofNusingN % 2, create a new node with this bit, and insert it at the beginning of the list. We update theheadto point to the new node and divideNby2to move to the next bit.
-
-
Printing the List: The
printListfunction traverses the linked list and prints each node’s data, using " → " to show connections.
Time Complexity:
The time complexity is O(log N) because we process each bit of N, which takes logarithmic time relative to the value of N.
Space Complexity:
The space complexity is O(log N) for the linked list, as we create a node for each bit in the binary representation of N.