There are no items in your cart
Add More
Add More
Item Details | Price |
---|
This blog explains various insertion techniques in a single linked list and also includes Python code examples for better understanding. These operations are fundamental for dynamic memory management and are frequently used in algorithmic problem-solving.
Sun Jan 12, 2025
In this blog, we will explore how to insert nodes at various positions in a single linked list and the process of traversing through the list. We will explain each operation step-by-step, using Python code to demonstrate how these techniques work in practice.
What is Linked List Traversing?
Traversing a linked list means visiting each node one by one, starting from the head node. The process continues until the `next` pointer of the current node is `None`, indicating the end of the list.
The traversal process can also be used to count the number of nodes in the list using a helper function like `getLength`. Here's how you can traverse a linked list:
def traverse(self):
current = self.head
while current:
print(current.data)
current = current.next
Insertion Method: To insert a node at the beginning:
Time Complexity: O(1) — This operation is performed in constant time as it directly modifies the head pointer without needing to traverse the list.
Example in Python:
def insert_at_beginning(self, data):
new_node = Node(data, self.head) # New node points to current head
self.head = new_node # Update the head to point to the new node
Insertion Method (for non-empty linked lists):
Time Complexity: O(n) — This operation requires traversal to the last node, so the time complexity is linear in terms of the number of nodes.
Example in Python:
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data) # If the list is empty, set the head to the new node
else:
current = self.head
while current.next: # Traverse until the last node
current = current.next
current.next = Node(data) # Set the last node's next to the new node
Insertion Method: To insert a node at a specified position:
Time Complexity: O(n) — This operation requires traversal to the given index, making the time complexity linear in terms of the number of nodes.
Example in Python:
def insert_at_position(self, index, data):
if index < 0 or index >= self.get_length():
raise Exception("Invalid index")
if index == 0:
self.insert_at_beginning(data)
return
current = self.head
count = 0
while current:
if count == index - 1:
new_node = Node(data, current.next)
current.next = new_node
break
current = current.next
count += 1
Efficiency Considerations:
These insertion operations are essential for understanding linked lists, which are frequently used in problems involving dynamic data storage and in managing data structures like stacks and queues.