This post provides an overview of several methods to implement a linked list in Python.

A Linked List node consists of a data field and a reference to the next node in the list. We can use a constructor to initialize the data and the next field for a node allocated in the memory during runtime.

Practice this problem

 
There are several ways to construct a singly linked list in Python:

1. Standard Solution

The standard solution adds a single node to the head end of the list, making a list look a bit like a stack.

Linked List Construction

This is demonstrated below where the head node is updated in the caller.

Download  Run Code

2. Naive method

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

Linked List Implementation

 
Here’s what the code would look like:

Download  Run Code

 
We can write the above code in a single line by passing the next node as an argument to the Node constructor:

Download  Run Code

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

 
Continue Reading:

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

 
Also See:

Linked List Implementation in C

Linked List Implementation in C++

Linked List Implementation in Java