Learn advanced linked list operations including insertion and deletion at specific positions.
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.length = 0
# Add a node to the end of the list
def append(self, value):
new_node = Node(value)
self.length += 1
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
# Insert a node at a specific position
def insert_at_position(self, position, value):
# If position is out of range
if position < 0 or position > self.length:
return False
new_node = Node(value)
# Insert at the beginning
if position == 0:
new_node.next = self.head
self.head = new_node
self.length += 1
return True
# Insert at any other position
current = self.head
previous = None
index = 0
while index < position:
previous = current
current = current.next
index += 1
new_node.next = current
previous.next = new_node
self.length += 1
return True
list_ = LinkedList()
list_.append(1)
list_.append(3)
list_.append(4)
# Insert 2 at position 1 (between 1 and 3)
list_.insert_at_position(1, 2)
# Output: 1 -> 2 -> 3 -> 4
class LinkedList:
# ... previous methods
def remove_at_position(self, position):
# If the list is empty or position is out of range
if not self.head or position < 0 or position >= self.length:
return None
# Remove the first node
if position == 0:
removed_node = self.head
self.head = self.head.next
self.length -= 1
return removed_node.value
# Remove node at any other position
current = self.head
previous = None
index = 0
while index < position:
previous = current
current = current.next
index += 1
removed_node = current
previous.next = current.next
self.length -= 1
return removed_node.value
list_ = LinkedList()
list_.append(1)
list_.append(2)
list_.append(3)
list_.append(4)
# Remove node at position 2 (value 3)
removed = list_.remove_at_position(2)
print(removed) # 3
# Output: 1 -> 2 -> 4
Now that you've learned how to implement insertion and deletion at specific positions in a linked list, try these practice challenges:
Implement a method to reverse a linked list in-place.
class LinkedList:
# ... previous methods
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
Implement a method to find the middle node of a linked list using only one pass.
class LinkedList:
# ... previous methods
def find_middle(self):
slow = self.head
fast = self.head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
If you want more practice with linked lists, check out these LeetCode problems: