A linked list is a sequence of nodes in which each node has a data element and a reference to the node following it.  This forms a chain link of data storage. A linked list stores its data anywhere in memory. This gives a linked list enormous flexibility to expand itself. A linked list class is implemented here so that you understand how it works internally.

linked list implementation diagram

Table of Content


Map of linked list implementations

you are here

Part 1 – Linked list implementation
Part 2 – Doubly linked list implementation
Part 3 – Ciucular linked list implementation


Define linked list class

First, we define a Node class. Node class has two fields: data and next. The data stores the value. the next is the reference to the next node. LinkList class has two variables head and length. The head always points to the first node. Its initial value is null. The length is to keep track of the number of elements in the list.

Java

Javascript

Python


Add element

To add an element, we have to create the node with the value first. You can add the node at the front, anywhere in the middle, or at the end, based on the design. Here is the code to add at the front and at the end.

Java

Javascript

Python

Doodle

linked list append


Delete by key

To delete an element by the key, declare a p node reference to the head, and declare a prev node to be null. The prev represents the previous node of the current node p. Compare the p node’s value with the key. If the data is not equal, assign the prev node to the p node, and the p node points to its next node. Repeat until you find the node with the value the same as the key. Now link the prev’s next to this node’s next. If no node is found when reaches the end, return null.

Java

Javascript

Python

Doodle

linked list delete


Search by key

To search by key, declare the p node reference to head. Compare the data with the key. If they are not equal, move the reference to the next node. Repeat until you find the node with a value the same as the key. Return this node. If no node is found when the reference reaches the end, return null.

Java

Javascript

Python

Doodle

linked list search


Print elements

Starting from the head, print the value of each node. Then follow the chain of reference from link to link until reaching the end.

Java

Javascript

Python

Doodle

linked list print


Free download

Download Linked list implementation in Java, JavaScript and Python
Download all Data Structures implementations in Java