Skip to main content

Command Palette

Search for a command to run...

Creating and Managing a Linked List in Python

Published
2 min read

Creating and Managing a Linked List in Python

In this blog post, we'll explore how to create a linked list in Python, including basic operations like insertion, deletion, and reversal. Linked lists are fundamental data structures that allow for efficient insertions and deletions, making them an essential part of any programmer's toolkit.

What is a Linked List?

A linked list consists of nodes, where each node contains data and a reference (or link) to the next node in the sequence. Unlike arrays, linked lists do not require contiguous memory allocation, making them more flexible in certain situations.

Implementing a Linked List

Here’s a simple implementation of a singly linked list in Python:

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

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

    def insert(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        last = self.head
        while last.next:
            last = last.next
        last.next = new_node

    def delete(self, key):
        curr = self.head
        prev = None
        while curr and curr.data != key:
            prev = curr
            curr = curr.next
        if not curr:
            return
        if prev:
            prev.next = curr.next
        else:
            self.head = curr.next

    def reverse(self):
        prev = None
        curr = self.head
        while curr:
            next_node = curr.next
            curr.next = prev
            prev = curr
            curr = next_node
        self.head = prev

    def display(self):
        curr = self.head
        while curr:
            print(curr.data, end=" -> ")
            curr = curr.next
        print("None")

How to Use the Linked List

To utilize the LinkedList class, you can perform various operations:

# Create a linked list
ll = LinkedList()

# Insert elements
ll.insert(10)
ll.insert(20)
ll.insert(30)

# Display the list
print("Linked List:")
ll.display()

# Delete an element
ll.delete(20)
print("After deleting 20:")
ll.display()

# Reverse the list
ll.reverse()
print("Reversed Linked List:")
ll.display()

Conclusion

In this blog post, we've implemented a simple linked list in Python and demonstrated how to perform basic operations like insertion, deletion, and reversal. Linked lists provide flexibility and efficiency for dynamic data storage, making them a vital concept in data structures and algorithms.

For further reading on linked lists and other data structures, check out resources like GeeksforGeeks or LeetCode.


More from this blog

Amazon S3 Storage Classes

43 posts