Delete a node in linked list in python

Delete a node in linked list  in python



To delete a node from a linked list in Python, you can follow these steps:

  1. Create a reference to the node you want to delete. This can be done by iterating through the linked list until you find the node you want to delete.
  2. If the node you want to delete is the head node (i.e., the first node in the linked list), you can simply set the head reference to point to the next node in the list. 
    head = head.next
  3. If the node you want to delete is not the head node, you can set the next reference of the previous node to point to the next node, effectively skipping over the node you want to delete.
    prev.next = node.next

Full code 

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

class LinkedList:
    def __init__(self):
        self.head = None

    def delete_node(self, data):
        node = self.head
        if node and node.data == data:
            self.head = node.next
            return
        prev = None
        while node and node.data != data:
            prev = node
            node = node.next
        if node is None:
            return
        prev.next = node.next

linked_list = LinkedList()
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
linked_list.head = node1
node1.next = node2
node2.next = node3
linked_list.delete_node(2)

In this example, the delete_node method takes a data value as input and searches for the node with that data value in the linked list. If the node is found, it is deleted by updating the next reference of the previous node to skip over it.





Post a Comment

0 Comments