C++ Singly Linked List – How to add a node

A singly linked list is a linear data structure that stores the address or reference of the next node in the list:

Singly linked lists are typically used when data is dynamic and changing at runtime. The amount nodes, that can be stored, isn’t a fixed number and can increase in size. This makes it useful to use if there is an unknown number of nodes needed.

How to implement a singly linked list

The first thing we want to do is create our Node struct to hold the data of each Node and the next Node along. I am using a typedef here to neaten up the code, alternatively you could write it like this:

As you can see, the typedef makes it easier to read and manage. I forgot to mention that the struct is written in private because we don’t need to access these values outside of the class.

Next we need to create some simple functions to call outside of the class

Lets focus on the AddNode function for now, this function will handle putting data at the end of the list

If we pass our first value into this function, our Head variable will be set as NULL as we haven’t yet passed a value into it. So we can just set Head = n which sets its int data to the value passed and the next Node to NULL. When we pass in our second value, Head won’t be set to NULL anymore and we can input our second value by setting the Curr variable to the Head variable then traversing through the list until we reach the end (see the while loop) then we link the Node using Curr->next = n

We dont have a way to print out the values we have passed yet so lets work on that next:

The first thing we do is set Curr variable to the first Node in the list (Head). Head will always point to the first Node. Then we can have a while loop to check that the current data isnt NULL. Then in the while loop we just print it to console and set the Curr value to the next Node in the list to print the next value, aslong as it doesn’t return as NULL.

Now we can call a few functions in our main.cpp file. This will output the values 5, 8, 3 (in that order).

In the next tutorial, I will be focusing on the InsertStart() and DeleteNode() functions.

Click here to see how to implement a template class with the Linked List (not yet written).

Leave a Comment

Your email address will not be published.