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

Other Linked List Posts:

My social media

LinkedIn Twitter Original Blog Github HackerRank

--

--

--

iOS Software Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Create an NFT Contract Factory with Metadata stored on IPFS

Cropping Images in Swift and the Basics of UIImage, CGImage and CIImage

Leetcode 314. Binary Tree Vertical Order Traversal Python solution

Adopt Session-Based Testing to Effectively Monitor Product Quality

Service to Service authentication using OAuth2 for AWS Serverless stack

Why are architectural patterns important while using Flutter

8 reasons Page-Object Model is overrated

Display Video 360 User Audit Solution

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Almost Engineer

Almost Engineer

iOS Software Developer

More from Medium

5/13 leet code

Dive Deep into Quicksort

How to approach a Backtracking Problem — Sudoku example

Backtracking paradigm on a high level

FHIR for Developers: Part 3