Ask Your Question
1

How can a node be removed from a linked list that is singly-linked?

asked 2023-07-12 23:18:20 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-12 23:34:02 +0000

qstack gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-12 23:18:20 +0000

Seen: 9 times

Last updated: Jul 12 '23