Delete and Insert a Node in a Linked List in Python
Stephen Cheng
Intro
Basic things we can do with linked lists are:
Traversal
Remove a node
Insert a node
Sort
For simplicity, singly linked lists will be used to explain these operations below.
Delete a Node in a Linked List
In this case we have the link (or pointer or address) to a node that we want to delete. It is important to connect the nodes on each side of the node before deleting it, so that the linked list is not broken. So before deleting the node, we need to get the next pointer from the previous node, and connect the previous node to the new next node before deleting the node in between.
In a singly linked list, like we have here, to get the next pointer from the previous node we actually need traverse the list from the start, because there is no way to go backwards from the node we want to delete.
In the code below, the algorithm to delete a node is moved into a function called deleteSpecificNode, the return value is the new head of the linked list. So for example, if the node to be deleted is the first node, the new head returned will be the next node.
Inserting a node into a linked list is very similar to deleting a node, because in both cases we need to take care of the next pointers to make sure we do not break the linked list. To insert a node in a linked list we first need to create the node, and then at the position where we insert it, we need to adjust the pointers so that the previous node points to the new node, and the new node points to the correct next node.
In the insertNodeAtPosition function below, the return value is the new head of the linked list. So for example, if the node is inserted at the start of the linked list, the new head returned will be the new node.
classNode: def__init__(self, data): self.data = data self.next = None
deftraverseAndPrint(head): currentNode = head while currentNode: print(currentNode.data, end=" -> ") currentNode = currentNode.next print("null")
definsertNodeAtPosition(head, newNode, position): if position == 1: newNode.next = head return newNode currentNode = head for _ in range(position - 2): if currentNode isNone: break currentNode = currentNode.next
newNode.next = currentNode.next currentNode.next = newNode return head