Linked list data structure: A linked list is a sequence of nodes in which each node has 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.

linked list diagram

Table of Content


Define classes

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 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 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 reach the end, return null.

Java

Javascript

Python

Doodle

linked list delete


Search by key

To search by key, declare 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 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

Download Java, JavaScript and Python code
Linked list animated visual
Data structures and Java collections