img

Software Development Blog

Back

Print the Elements of a Linked List. HackerRank Exercise

This exercise is a part of my Linked List topic.

If you're new to linked lists, this is a great exercise for learning about them. Given a pointer to the head node of a linked list, print its elements in order, one element per line. If the head pointer is null (indicating the list is empty), don’t print anything.

Input Format

The first line of input contains n, the number of elements in the linked list. 
The next n  lines contain one element each, which are the elements of the linked list.

Explanation

This is a classic Linked List Node realization below

The current exercise is the easiest exercise about Linked List. As you understand from the theoretical part - Linked List Node has a reference on the next element in the next variable. The last node in a list has null in the next variable. So it is a way to check if the current node is a last in List.

In the first line, we imported the node model. It will the same for another Linked List exercises

Loop while is the most convenient way to go through Linked List because it is easy to check if the next variable isn't null. So in the example, above we just run a loop through Linked List while the next variable isn't null.

Testing

Here we created 3 nodes and link them through the next variable. As a result, our function returns 1, 2, 3.

Github project

My social media

LinkedIn Twitter Original Blog Github HackerRank

Recent Posts

What are UUID identifiers in Swift?

READ MORE

How to use Comparable protocol

READ MORE