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.

Table of Content


Define classes

Node class has two fields: data stores the value and next is the reference to the next node. LinkList class has a variable head. head always points to the first node. Its initial value is null.

Java

Javascript

Python


Add element

To add an element, you 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 your 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, assign a current node reference to the head, and declare a previous node variable to be null. Compare the current node’s value with the key. If the data is not equal to the key, assign the previous node to the current node, and current nodes points to the next node. Repeat until you find the node with the value the same as the key. Now link the previous node’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, assign the current 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
Data structures and Java collections