Print the Elements of a Linked List is a coding challenge with easy difficulty in the HackerRank data structures category. In this blog post, we’ll discuss how we can solve it in JavaScript in O(n) time and O(1) space complexity.
Problem Statement
Given a pointer to the head node of a linked list, print each node’s data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print.
Read full details and access the challenge on Print the Elements of a Linked List | HackerRank
Solution
function printLinkedList(head) {
while (head) {
console.log(head.data);
head = head.next;
}
}
Time Complexity : O(n)
Space Complexity : O(1)
This is a standard operation for a linked list.
The challenge also provided a reference for the linked list’s properties.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
To print all the data inside we just have to traverse through all the nodes. To do this, we use a while loop, as long as the node (identified by head) is not null, we keep printing it’s data and move to the next node.
We’re traversing through the linked list once, so we have O(n) time complexity and since we use no extra space, we have O(1) space complexity.
Conclusion
That’s how you can solve the Print the Elements of a Linked List Challenge in HackerRank.
This is a good practice to solidify your knowledge on linked lists.
If you have an approach different from mine, please do comment below!
Check out the rest of my blog for more helpful contents on Data Structures and Algorithms in JavaScript! We’ll also discuss more HackerRank solutions using JavaScript in this blog!
See you next post!