Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To remove a node from a singly-linked list, follow these steps:

  1. Find the node to be removed and its previous node.
  2. Update the previous node's next pointer to point to the node after the one being removed.
  3. Delete the node being removed.

Here is an example Python code to remove a node from a singly-linked list:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def remove_node(head, value):
    # If head node itself holds the key to be deleted
    if head is not None:
        if head.data == value:
            head = head.next
            return head

    # Search for the key to be deleted
    current_node = head

    while current_node is not None:
        if current_node.data == value:
            break
        prev_node = current_node
        current_node = current_node.next

    # If key was not present in linked list
    if current_node is None:
        return head

    # Unlink the node from linked list
    prev_node.next = current_node.next

    return head