To remove a node from a singly-linked list, follow these steps:
next
pointer to point to the node after the one 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
Asked: 2023-07-12 23:18:20 +0000
Seen: 11 times
Last updated: Jul 12 '23