how-to-create-a-linked-list-in-python.html

How to Create a Linked List in Python: A Comprehensive Guide

Linked lists are a fundamental data structure used in computer science. They provide a way to store collections of data, allowing for efficient insertion and deletion. In this article, we will explore how to create a linked list in Python, covering the definitions, use cases, and actionable insights to help you implement this data structure effectively.

What is a Linked List?

A linked list is a linear data structure where elements, known as nodes, are stored in a sequence. Each node contains two main components:

  1. Data: The value or information stored in the node.
  2. Pointer/Reference: A reference to the next node in the sequence.

Unlike arrays, linked lists do not require contiguous memory allocation, which allows for dynamic memory usage. This makes linked lists efficient for certain operations, especially when dealing with large datasets.

Use Cases of Linked Lists

Linked lists are commonly used in various applications, such as:

  • Dynamic memory allocation: They allow for efficient memory usage when the size of data is unknown beforehand.
  • Implementing stacks and queues: Linked lists can be used to create these essential data structures.
  • Graph representation: Adjacency lists in graph theory can be implemented using linked lists.
  • Undo functionality in applications: Linked lists can store states that can be traversed backward.

Types of Linked Lists

Before diving into the implementation, it's essential to understand the different types of linked lists:

  1. Singly Linked List: Each node points to the next node, and the last node points to None.
  2. Doubly Linked List: Each node points to both the next and the previous nodes.
  3. Circular Linked List: The last node points back to the first node, forming a circle.

In this guide, we will focus on creating a Singly Linked List.

Step-by-Step Instructions to Create a Singly Linked List in Python

Step 1: Define the Node Class

First, we need a class to represent each node in our linked list. This class will have an initializer to set the data and the pointer to the next node.

class Node:
    def __init__(self, data):
        self.data = data  # Assign data to the node
        self.next = None  # Initialize the next pointer as None

Step 2: Define the Linked List Class

Next, we will create a LinkedList class to manage the nodes. This class will include methods to insert, display, and delete nodes.

class LinkedList:
    def __init__(self):
        self.head = None  # Initialize the head of the list as None

    def insert(self, data):
        new_node = Node(data)  # Create a new node
        if not self.head:  # If the list is empty
            self.head = new_node  # Set the new node as the head
            return
        last = self.head
        while last.next:  # Traverse to the last node
            last = last.next
        last.next = new_node  # Link the last node to the new node

    def display(self):
        current = self.head
        while current:  # Traverse the list
            print(current.data, end=" -> ")
            current = current.next
        print("None")  # End of the list

Step 3: Implementing the Linked List

Now that we have our Node and LinkedList classes defined, let's see how to use them to create a linked list and insert some data.

# Create a new linked list
linked_list = LinkedList()

# Insert data into the linked list
linked_list.insert(10)
linked_list.insert(20)
linked_list.insert(30)

# Display the linked list
linked_list.display()

Step 4: Additional Operations

To make our linked list more functional, we can implement additional methods such as deleting a node and searching for a node.

Delete a Node

def delete_node(self, key):
    current = self.head

    # If the head node itself holds the key
    if current and current.data == key:
        self.head = current.next  # Change head
        current = None  # Free memory
        return

    # Search for the key to be deleted
    prev = None
    while current and current.data != key:
        prev = current
        current = current.next

    # If the key was not present in the linked list
    if current is None:
        return

    # Unlink the node from the linked list
    prev.next = current.next
    current = None  # Free memory

Search for a Node

def search(self, key):
    current = self.head
    while current:
        if current.data == key:
            return True  # Key found
        current = current.next
    return False  # Key not found

Step 5: Testing the Linked List

You can add the delete and search methods to the LinkedList class and test them similarly.

# Test deletion
linked_list.delete_node(20)
linked_list.display()  # Should display: 10 -> 30 -> None

# Test search
print(linked_list.search(30))  # Output: True
print(linked_list.search(20))  # Output: False

Conclusion

Creating a linked list in Python is straightforward with the use of classes. By following the steps outlined in this article, you can efficiently implement a Singly Linked List, perform essential operations, and adapt this structure to fit your programming needs. Understanding linked lists will enhance your coding skills and prepare you for more complex data structures.

Whether you're a beginner or a seasoned programmer, mastering linked lists is crucial for efficient data management and manipulation in Python. Start implementing linked lists today and explore their many applications in your projects!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.