Check if linked list is sorted (Iterative and Recursive) in Python

PythonServer Side ProgrammingProgramming

Suppose we have a linked list we have to define two functions to check whether the linked list is sorted in non-increasing order or not. One of the method will work as iterative manner and another one in recursive manner.

So, if the input is like L = [15, 13, 8, 6, 4, 2], then the output will be True.

To solve this, we will follow these steps −

  • Define a function solve_iter(). This will take head
  • if head is null, then
    • return True
  • while next of head is not null, do
    • current := head
    • if value of current <= value of (next of current), then
      • return False
    • head := next of head
  • return True
  • Define a function solve_rec() . This will take head
  • if head is null or next of head is null, then
    • return True
  • return true when (val of head > value of (next of head) is not 0 and solve_rec(next of head) is true) otherwise false


Let us see the following implementation to get better understanding −

 Live Demo

class ListNode:
   def __init__(self, data, next = None):
      self.val = data = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
         ptr = = ListNode(element)
   return head
def solve_iter(head):
   if head == None:
      return True
   while != None:
      current = head
      if current.val <=
         return False
      head =
   return True
def solve_rec(head):
   if head == None or == None:
      return True
   return head.val > and solve_rec(
L = make_list([15, 13, 8, 6, 4, 2])


[15, 13, 8, 6, 4, 2]


Published on 19-Jan-2021 09:17:00