Skip to main content

Command Palette

Search for a command to run...

Linked List Implementation in Python

Published
2 min readView as Markdown
A

Aspiring DevOps Engineer • Sharing my knowledge via blogs

This program demonstrates how to create a linked list, insert elements, delete elements, reverse the list, and display the list.

Step 1: Define the Node Class

The Node class represents each element in the linked list.

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

Step 2: Define the Linked List Class

The LinkedList class manages the linked list operations.

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):
        current = self.head
        prev = None

        if current and current.data == key:
            self.head = current.next
            current = None
            return

        while current and current.data != key:
            prev = current
            current = current.next

        if not current:
            return

        prev.next = current.next
        current = None

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

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

Step 3: Using the Linked List

Here’s how you can use the LinkedList class to perform operations:

ll = LinkedList()

ll.insert(10)
ll.insert(20)
ll.insert(30)

print("Linked List:")
ll.display()

ll.delete(20)
print("After deleting 20:")
ll.display()

ll.reverse()
print("Reversed Linked List:")
ll.display()

Conclusion

This program provides a basic implementation of a singly linked list with functionalities for inserting, deleting, displaying, and reversing the list. You can expand upon this by adding more features as needed! If you have any questions or need further assistance, feel free to ask!

More from this blog

Blissman's thoughts

104 posts