📄 Need a professional CV? Try our Resume Builder! Get Started

Creating a Single Linked List

In this blog post, we will go through a step-by-step guide on implementing a singly linked list in Python. Linked lists are a fundamental data structure and provide flexibility over arrays as they allow dynamic memory management.

Sun Jan 5, 2025

1. Understanding Linked Lists

A linked list is a linear data structure where each element, called a node, contains two parts:

  • Data: The value stored in the node.
  • Next: A reference (or pointer) to the next node in the sequence.

The list is accessed through a head pointer, which points to the first node. An empty list has a head of None.

2. The Node Class

We define a Node class to represent each node in the list:

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

Explanation:

  • __init__(self, data, next=None): The constructor initializes a new node with the given data. The next pointer is initialized to None, indicating the end of the list or an unlinked node.

3. The LinkedList Class

The LinkedList class manages the collection of nodes:

class LinkedList:
    def __init__(self):
        self.head = None

Explanation:

  • __init__(self): The constructor initializes an empty linked list by setting the head to None.

4. Printing the Linked List

A print_list method helps visualize the list's contents:

def print_list(self):
    if self.head is None:
        print("The linked list is empty")
        return
    current = self.head
    while current:
        print(current.data, end=" -> " if current.next else "")
        current = current.next
    print()

Explanation:

  • The method checks for an empty list (self.head is None).
  • It iterates through the list using a while loop, printing each node's data.
  • The end=" -> " adds the arrow between elements, except for the last one.

5. Creating a Linked List

Here's how to create a linked list and connect nodes:

# Create nodes
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)

# Create linked list and set head
linked_list = LinkedList()
linked_list.head = node1

# Link the nodes
node1.next = node2
node2.next = node3

# Print the linked list
linked_list.print_list()  # Output: 1 -> 2 -> 3

6. Inserting at the Beginning

The insert_at_beginning method adds a new node at the start of the list:

def insert_at_beginning(self, data):
    new_node = Node(data)
    new_node.next = self.head
    self.head = new_node

Explanation:

  • A new node is created with the given data.
  • The new node's next pointer is set to the current head.
  • The head of the list is updated to point to the new node.

7. Example: Inserting at the Beginning

Here is how the linked list looks after inserting a node at the beginning:

linked_list.insert_at_beginning(0)
linked_list.print_list()  # Output: 0 -> 1 -> 2 -> 3

Creating a Singly Linked List: Visual Guide

Node Created
Current Element
Inserting

Step 1: Create Nodes

1
2
3
We create three nodes: Node(1), Node(2), Node(3)

Step 2: Link Nodes

1
2
3
Link the nodes: 1 -> 2 -> 3

Step 3: Insert New Node at Beginning

0
1
2
3
Inserting a new node with value 0 at the beginning

Final List

0
1
2
3
The final linked list: 0 -> 1 -> 2 -> 3

Algorithm Summary

  • Time Complexity: O(1) for insertion at the beginning
  • Space Complexity: O(n) for storing the nodes
  • In-place data structure
  • Dynamic memory allocation

8. Full Code

The complete code is shown below:

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None

    def print_list(self):
        if self.head is None:
            print("The linked list is empty")
            return
        current = self.head
        while current:
            print(current.data, end=" -> " if current.next else "")
            current = current.next
        print()

    def insert_at_beginning(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

# Example Usage
linked_list = LinkedList()
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)

linked_list.head = node1
node1.next = node2
node2.next = node3

print("Initial List:")
linked_list.print_list()

linked_list.insert_at_beginning(0)
print("\nList after inserting at the beginning:")
linked_list.print_list()

linked_list2 = LinkedList()
print("\nEmpty List:")
linked_list2.print_list()