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.