Programming & Development / April 19, 2025

Linked Lists in Python: Insertion, Deletion, Reversal, and Node Manipulation

linked lists python data structures insertion deletion reversal nodes singly linked list coding interview leetcode

Linked lists are linear data structures where elements (called nodes) are linked using pointers. Unlike arrays, linked lists allow efficient insertions and deletions without shifting elements.

Python doesn't have a built-in LinkedList class like Java, but we can easily implement one using custom classes.

๐Ÿ”— Node Structure in Python

python

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

๐Ÿ—๏ธ Singly Linked List

๐Ÿ“ฅ Insertion (at end)

python

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
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node

๐Ÿงน Deletion (by value)

python

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

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

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

        if current:
            prev.next = current.next

๐Ÿ”„ Reversal

python

    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

๐Ÿ“‹ Print the List

python

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

๐Ÿงช Example Usage

python

ll = LinkedList()
ll.insert(1)
ll.insert(2)
ll.insert(3)
ll.print_list()       # 1 -> 2 -> 3 -> None

ll.delete(2)
ll.print_list()       # 1 -> 3 -> None

ll.reverse()
ll.print_list()       # 3 -> 1 -> None

๐Ÿง  Final Thoughts

Linked lists provide dynamic memory allocation and are useful for implementing stacks, queues, and other complex structures. Though slightly more manual in Python, understanding linked list operations is essential for interview preparation and algorithmic thinking.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex