Master advanced linked list operations including searching, insertion, and deletion. Learn efficient techniques for manipulating linked data structures.
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.length = 0
def search(self, value):
current = self.head
while current:
if current.value == value:
return current
current = current.next
return None
def insert(self, value, index):
if index < 0 or index > self.length:
return False
new_node = Node(value)
if index == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for _ in range(index - 1):
current = current.next
new_node.next = current.next
current.next = new_node
self.length += 1
return True
def delete(self, index):
if index < 0 or index >= self.length:
return None
if index == 0:
deleted_node = self.head
self.head = self.head.next
else:
current = self.head
for _ in range(index - 1):
current = current.next
deleted_node = current.next
current.next = current.next.next
self.length -= 1
return deleted_node.value
list = LinkedList()
# Insert elements
list.insert(10, 0) # [10]
list.insert(20, 1) # [10, 20]
list.insert(15, 1) # [10, 15, 20]
# Search for element
print(list.search(15)) # Node object with value 15
# Delete element
print(list.delete(1)) # 15
# List is now [10, 20]
Implement a method to search for a value starting from the end of the linked list.
Implement a method to insert multiple values at a specified position.
Implement a method to delete all nodes with a specific value.
Note: Previously, this course referenced the CodeSignal Arcade for practice, which is no longer available. The LeetCode problems below follow the same principles and are excellent for practicing linked list operations.