A LEVEL COMPUTING
Data Structures
Theory
7. Deleting a node from a linked list
One of the basic algorithms needed to maintain the list is DELETE. This is explained by carrying on with the example from the previous page.
But basically the DELETE algorithm adjusts the pointer of the relevant nodes to make sure the list remains in the correct order after the node is removed
Example: Storing an alphabetic list of names in a linked list
The diagram above shows the final form of the linked list. This time the task is to remove a node from the linked list
DELETE ALGORITHM
- Starting with the first node pointed to by the start pointer
- Is this the node to be removed?
- Case 1: The node to be removed is the first one.
- Adjust the start pointer to point to the next node
- Remove the original node
- Mark the memory it used as free once more
- Task complete
- Case 2: The node to be removed is an intermediate one
- Examine the next node by using the node pointers to move from node to node until the correct node is identified
- Node found
- Copy the pointer of the removed node into temporary memory
- Remove the node from the list and mark the memory it was using as free once more
- Update the previous node's pointer with the address held in temporary memory
- Task complete
- Case 3: It is the last node to be removed
- Remove the last node from the list
- Mark the prior node with a null pointer
- Mark the memory the deleted node used as free once more.
- Task complete
- Case 4: Node cannot be found
- Return an error message to the calling code
- Task complete
Copyright © www.teach-ict.com