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

A linked list is sorted in non-increasing order when each node's value is greater than or equal to the next node's value. We can check this condition using both iterative and recursive approaches.

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

LinkedList Node Structure

First, let's define the basic structure of a linked list node ?

class ListNode:
    def __init__(self, data, next=None):
        self.val = data
        self.next = next

def make_list(elements):
    if not elements:
        return None
    head = ListNode(elements[0])
    current = head
    for element in elements[1:]:
        current.next = ListNode(element)
        current = current.next
    return head

Method 1: Iterative Approach

The iterative method traverses the list once and compares adjacent nodes ?

def solve_iter(head):
    # Empty list is considered sorted
    if head is None:
        return True
    
    # Traverse the list and check each pair
    while head.next is not None:
        if head.val < head.next.val:  # If current < next, not non-increasing
            return False
        head = head.next
    
    return True

# Test the iterative approach
elements = [15, 13, 8, 6, 4, 2]
L = make_list(elements)
print("Iterative result:", solve_iter(L))
Iterative result: True

Method 2: Recursive Approach

The recursive method checks the current pair and recursively validates the rest of the list ?

def solve_rec(head):
    # Base cases: empty list or single node
    if head is None or head.next is None:
        return True
    
    # Check current pair and recurse for the rest
    return head.val >= head.next.val and solve_rec(head.next)

# Test the recursive approach
elements = [15, 13, 8, 6, 4, 2]
L = make_list(elements)
print("Recursive result:", solve_rec(L))
Recursive result: True

Complete Example

Let's test both methods with different test cases ?

class ListNode:
    def __init__(self, data, next=None):
        self.val = data
        self.next = next

def make_list(elements):
    if not elements:
        return None
    head = ListNode(elements[0])
    current = head
    for element in elements[1:]:
        current.next = ListNode(element)
        current = current.next
    return head

def solve_iter(head):
    if head is None:
        return True
    while head.next is not None:
        if head.val < head.next.val:
            return False
        head = head.next
    return True

def solve_rec(head):
    if head is None or head.next is None:
        return True
    return head.val >= head.next.val and solve_rec(head.next)

# Test cases
test_cases = [
    [15, 13, 8, 6, 4, 2],  # Non-increasing: True
    [1, 2, 3, 4, 5],       # Increasing: False
    [5, 5, 5, 5],          # Equal values: True
    [10]                   # Single element: True
]

for i, elements in enumerate(test_cases, 1):
    L = make_list(elements)
    iter_result = solve_iter(L)
    L = make_list(elements)  # Recreate for recursive test
    rec_result = solve_rec(L)
    print(f"Test {i}: {elements}")
    print(f"Iterative: {iter_result}, Recursive: {rec_result}")
    print()
Test 1: [15, 13, 8, 6, 4, 2]
Iterative: True, Recursive: True

Test 2: [1, 2, 3, 4, 5]
Iterative: False, Recursive: False

Test 3: [5, 5, 5, 5]
Iterative: True, Recursive: True

Test 4: [10]
Iterative: True, Recursive: True

Comparison

Approach Time Complexity Space Complexity Best For
Iterative O(n) O(1) Memory-efficient
Recursive O(n) O(n) Clean, readable code

Conclusion

Both approaches have O(n) time complexity but differ in space usage. The iterative method uses constant space while the recursive method uses O(n) space due to function call stack. Choose iterative for better memory efficiency or recursive for cleaner code.

Updated on: 2026-03-25T15:16:37+05:30

617 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements