Delete Node in a Linked List in Python

PythonServer Side ProgrammingProgramming

Suppose we have a linked list with few elements. Our task is to write a function that will delete the given node from the list. So if the list is like 1 → 3 → 5 → 7 → 9, and after deleting 3, it will be 1 → 5 → 7 → 9.

Consider we have the pointer ‘node’ to point that node to be deleted, we have to perform these operations to delete the node −

  • node.val = node.next.val
  • node.next = node.next.next

Example (Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)
   return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')
class Solution(object):
   def deleteNode(self, node, data):
      """
      :type node: ListNode
      :rtype: void Do not return anything, modify node in-place instead.
      """
      while node.val is not data:
         node = node.next
      node.val = node.next.val
      node.next = node.next.next
head = make_list([1,3,5,7,9])
ob1 = Solution()
ob1.deleteNode(head, 3)
print_list(head)

Input

linked_list = [1,3,5,7,9]
data = 3

Output

[1, 5, 7, 9, ]
raja
Published on 09-Jan-2020 12:17:24
Advertisements