Code With Python
39.2K subscribers
887 photos
27 videos
22 files
769 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Topic: Linked Lists in Python – Part 2: Insertion, Deletion, and Search Operations

---

Recap from Part 1

• A singly linked list consists of nodes, where each node holds data and a pointer to the next node.

• We've implemented basic append and display functions.

Now we’ll explore insertion at specific positions, deletion, and searching.

---

1. Insert at a Specific Position

def insert_at_position(self, index, data):
if index < 0:
raise IndexError("Index cannot be negative")

new_node = Node(data)

if index == 0:
new_node.next = self.head
self.head = new_node
return

current = self.head
for _ in range(index - 1):
if not current:
raise IndexError("Index out of bounds")
current = current.next

new_node.next = current.next
current.next = new_node


---

2. Delete a Node by Value

def delete_by_value(self, value):
if not self.head:
return

if self.head.data == value:
self.head = self.head.next
return

current = self.head
while current.next and current.next.data != value:
current = current.next

if current.next:
current.next = current.next.next


---

3. Delete a Node by Index

def delete_by_index(self, index):
if index < 0:
raise IndexError("Index cannot be negative")

if not self.head:
raise IndexError("List is empty")

if index == 0:
self.head = self.head.next
return

current = self.head
for _ in range(index - 1):
if not current.next:
raise IndexError("Index out of bounds")
current = current.next

if current.next:
current.next = current.next.next


---

4. Search for an Element

def search(self, value):
current = self.head
index = 0
while current:
if current.data == value:
return index
current = current.next
index += 1
return -1 # Not found


---

5. Complete Class with All Methods

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

def append(self, data): ...
def display(self): ...
def insert_at_position(self, index, data): ...
def delete_by_value(self, value): ...
def delete_by_index(self, index): ...
def search(self, value): ...


*(You can reuse the method definitions above.)*

---

Summary

• You can manipulate linked lists with insertions and deletions at any position.

• Searching through a singly linked list is O(n).

• Always check for edge cases: empty list, index bounds, and duplicates.

---

Exercise

• Write a method reverse() that reverses the linked list in-place and test it on a list of 5+ elements.

---

#DSA #LinkedList #Python #Insertion #Deletion #Search

https://t.iss.one/DataScience4
2