Program to delete n nodes after m nodes from a linked list in Python

PythonServer Side ProgrammingProgramming

Suppose we are given a linked list that has the start node as "head", and two integer numbers m and n. We have to traverse the list and delete some nodes such as the first m nodes are kept in the list and the next n nodes after the first m nodes are deleted. We perform this until we encounter the end of the linked list. We start from the head node, and the modified linked list is to be returned.

The linked list structure is given to us as −

Node
   value : <integer>
   next : <pointer to next node>

So, if the input is like elements = [1, 2, 3, 4, 5, 6, 7, 8], m = 3, n = 1, then the output will be [1, 2, 3, 5, 6, 7, ]

Every node after 3 nodes is deleted in this process, so in the end the linked list will look like below −

To solve this, we will follow these steps −

  • prev := head

  • curr := head

  • q := 0

  • p := 0

  • while curr is not null, do

    • q := q + 1

    • if q is same as m, then

      • for i in range 0 to n, do

        • if curr.next is not null, then

          • curr := next of curr

      • next of prev := next of curr

      • q := 0

    • prev := next of prev

    • curr := next of curr

  • return head

Example (Python)

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

 Live Demo

class ListNode:
   def __init__(self, val=0, next=None):
      self.val = val
      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(']')

def solve(head, m, n):
   prev = curr = head
   q = 0
   p = 0

   while curr:
      q += 1
      if q == m:
         for i in range(n):
            if curr.next is not None:
               curr = curr.next
         prev.next = curr.next
         q = 0

      prev = prev.next
      curr = curr.next

   return head

head = ListNode()
elements = [1, 2, 3, 4, 5, 6, 7, 8]
head = make_list(elements)
res = solve(head, 3, 1)
print_list(res)

Input

[1, 2, 3, 4, 5, 6, 7, 8], 3, 1

Output

[1, 2, 3, 5, 6, 7,]
raja
Published on 17-May-2021 12:09:59
Advertisements