Linked Lists allow us to add, remove, and traverse nodes efficiently without fixed-size limitations like arrays. Here are the three main operations:
Traversing means visiting each node one by one from the head till the end (where next is null).
def traverse(head):
current = head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
Adding a new node either at the beginning, end, or at a particular position involves pointing links correctly to keep the list connected.
# Insert at beginning
def insert_at_head(head, data):
new_node = Node(data)
new_node.next = head
return new_node
# Insert at end
def insert_at_end(head, data):
new_node = Node(data)
if not head:
return new_node
temp = head
while temp.next:
temp = temp.next
temp.next = new_node
return head
Removing a node requires finding it and changing the previous node's pointer to skip over the deleted node.
def delete_node(head, key):
temp = head
prev = None
if temp and temp.data == key:
return temp.next
while temp and temp.data != key:
prev = temp
temp = temp.next
if not temp:
return head
prev.next = temp.next
return head
class Node:
def __init__(self, data):
self.data = data
self.next = None
With these basic operations, you can create, modify, and traverse linked lists efficiently in your programs.