This post provides an overview of some available techniques to implement a linked list in C++ programming language.

We know that each node of a linked list contains a single data field and a pointer to the next node in the list.

 
The nodes of the linked list are allocated in the heap memory. We can use the new operator in C++ for dynamic memory allocation and the delete operator to deallocate the allocated memory.

Practice this problem

 
There are several methods to construct a singly linked list. Each is covered in detail below:

1. Naive method

A simple solution would be to allocate memory for all individual nodes of the linked list, set their data, and rearrange their pointers to build the complete list.

Linked List Implementation

Download  Run Code

2. Single Line

We can write the above code in a single line by passing the next node as an argument to the newNode() function:

Linked List Construction

Download  Run Code

3. Generic Method

Both above methods are not practical when the total number of nodes increases in the linked list. If the keys are given in any container, such as an array, vector, or set, we can easily construct a linked list by traversing the container, as shown below:

Download  Run Code

4. Standard Solution

The standard solution adds a single node to the head end of any list. This function is called push() since we are adding the link to the head end, making a list look a bit like a stack.

We know that C++ has its built-in & argument feature to implement reference parameters. If we append an & to the type of parameter, the compiler will automatically make the parameter operate by reference without disturbing the argument’s type.

Download  Run Code

5. Make head pointer global

We can construct a linked list by making the head pointer global, but this approach is not recommended since global variables are usually considered bad practice.

Download  Run Code

6. Return head from the push() function

Another common approach many programmers follow is to return the head node from the push() function and update the head in the caller. This is demonstrated below:

Download  Run Code

 
Continue Reading:

Linked List – Insertion at Tail | C, Java, and Python Implementation

 
Also See:

Linked List Implementation in C

Linked List Implementation in Java

Linked List Implementation in Python

 
References: http://cslibrary.stanford.edu/103/LinkedListBasics.pdf