Insert New Element into Linked List Before Given Position in Python



Suppose we have a list of elements; these elements are stored in a singly linked list. We also have a value pos and value val. We have to insert val before index pos of the linked list.

So, if the input is like nums = [1,5,3,6,8] pos = 3 val = 7, then the output will be [1,5,3,7,6,8]

To solve this, we will follow these steps −

  • new := create a linked list node with value same as val

  • if pos is same as 0, then

    • next of new := list_head

    • return new

  • temp := list_head

  • while temp is not null and pos is not same as 1, do

    • temp := next of temp

    • pos := pos - 1

  • next of new := next of temp

  • next of temp := new

  • return list_head

Example

Let us see the following implementation to get better understanding

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(']')

   def solve(list_head, pos, val):
      new = ListNode(val)
      if pos == 0:
         new.next = list_head
         return new

      temp = list_head
      while temp and pos != 1:
         temp = temp.next
         pos -= 1
      next = temp.next
      temp.next = new

   return list_head

nums = [1,5,3,6,8]
pos = 3
val = 7

list_head = make_list(nums)
list_head = solve(list_head, pos, val)
print_list(list_head)

Input

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

Output

[1, 5, 3, 7, 6, 8, ]
Updated on: 2021-10-11T07:35:37+05:30

966 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements