Program to swap nodes in a linked list in Python


Suppose we have a list L and another value k. We have to swap kth node from start and kth node from end and return the final list at end.

So, if the input is like L = [1,5,6,7,1,6,3,9,12] k = 3, then the output will be [1,5,3,7,1,6,6,9,12], the 3rd node from start is 6 and from end is 3, so they are swapped.

To solve this, we will follow these steps −

  • temp := L
  • for i in range 0 to k-2, do
    • temp := next of temp
  • firstNode := temp
  • secondNode := L
  • while next of temp is not null, do
    • secondNode := next of secondNode
    • temp := next of temp
  • swap value of firstNode and value of secondNode
  • return L

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(L, k):
   temp = L
   for i in range(k-1):
      temp = temp.next
   firstNode = temp
   secondNode = L
   while temp.next:
      secondNode = secondNode.next
      temp = temp.next
   firstNode.val , secondNode.val = secondNode.val , firstNode.val
   return L

L = [1,5,6,7,1,6,3,9,12]
k = 3
print_list(solve(make_list(L), k))

Input

[1,5,6,7,1,6,3,9,12], 3

Output

[1, 5, 3, 7, 1, 6, 6, 9, 12, ]

Updated on: 06-Oct-2021

752 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements