Open In App

Check if a linked list is sorted in non-increasing order

Last Updated : 29 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Linked List, The task is to check whether the Linked List is sorted in a non-increasing order.

Examples :  

Input : 8 -> 7 -> 5 -> 2 -> 1
Output: Yes

Input : 24 -> 12 -> 9 -> 11 -> 8 -> 2
Output: No

[Expected Approach – 1] Using Recursion – O(n) Time and O(n) Space:

The idea is to compare each node’s data with the next node’s data. If at any point the current node’s data is less than the next node’s data, return false. If the list is empty or has only one node, it is considered sorted in non-increasing order by default. Continue the recursion until the end of the list is reached.

Below is the implementation of the above approach:

C++
// C++ program to recursively check Linked List
// is sorted in descending order

#include <iostream>
using namespace std;

class Node {
  public:
    int data;
    Node *next;

    Node(int x) {
        data = x;
        next = NULL;
    }
};

// Recursive function to check if the linked list is 
// sorted in descending order
bool isSortedDescending(Node *curr) {
  
    // Base case: empty list or single node
    if (curr == NULL || curr->next == NULL) {
        return true;
    }

    // If current node's data is less than the next 
    // node's data, list is not sorted
    if (curr->data < curr->next->data) {
        return false;
    }

    // Recursion for the rest of the list
    return isSortedDescending(curr->next);
}

void printList(Node *head) {
  
  	Node *curr = head;
    while (curr != NULL) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {
  
    // singly linked list 10->8->5->2
    Node *head = new Node(10);
    head->next = new Node(8);
    head->next->next = new Node(5);
    head->next->next->next = new Node(2);

    cout << (isSortedDescending(head) ? "True" : "False") << endl;

    return 0;
}
C
// C program to recursively check Linked List
// is sorted in descending order
#include <stdio.h>

struct Node {
    int data;
    struct Node *next;
};

// Recursive function to check if the singly linked list 
// is sorted in descending order
int isSortedDescending(struct Node *curr) {
  
    // Base case: empty list or single node
    if (curr == NULL || curr->next == NULL) {
        return 1;
    }
    
    // If current node's data is less than the next node's
    // data, list is not sorted
    if (curr->data < curr->next->data) {
        return 0;
    }
    
    // Recursion for the rest of the list
    return isSortedDescending(curr->next);
}

void printList(struct Node *head) {
  	struct Node *curr = head;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("\n");
}

struct Node *createNode(int x) {
    struct Node *newNode = 
      	(struct Node *)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->next = NULL;
    return newNode;
}

int main() {
  
    // singly linked list 10->8->5->2
    struct Node *head = createNode(10);
    head->next = createNode(8);
    head->next->next = createNode(5);
    head->next->next->next = createNode(2);

    printf("%s\n", isSortedDescending(head) ? "True" : "False");
    return 0;
}
Java
// Java program to recursively check Linked List 
// is sorted in descending order 

class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

// Recursive function to check if the singly linked list 
// is sorted in descending order
class GfG {
    static boolean isSortedDescending(Node curr) {
      
        // Base case: empty list or single node
        if (curr == null || curr.next == null) {
            return true;
        }
        
        // If current node's data is less than the 
        // next node's data, list is not sorted
        if (curr.data < curr.next.data) {
            return false;
        }
        
        // Recursion for the rest of the list
        return isSortedDescending(curr.next);
    }

    static void printList(Node head) {
      	Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
      
        // singly linked list 10->8->5->2
        Node head = new Node(10);
        head.next = new Node(8);
        head.next.next = new Node(5);
        head.next.next.next = new Node(2);

        System.out.println(isSortedDescending(head) ? "True" : "False");
    }
}
Python
# Python3 program to recursively check
# Linked List is sorted in descending 
# order
 
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Recursive function to check if the singly linked list is
# sorted in descending order
def is_sorted_descending(curr):
  
    # Base case: empty list or single node
    if curr is None or curr.next is None:
        return True
    
    # If current node's data is less than the next node's 
	# data, list is not sorted
    if curr.data < curr.next.data:
        return False
    
    # Recursion for the rest of the list
    return is_sorted_descending(curr.next)

def print_list(head):
    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next
    print()

if __name__ == "__main__":
  
    # singly linked list 10->8->5->2
    head = Node(10)
    head.next = Node(8)
    head.next.next = Node(5)
    head.next.next.next = Node(2)

    print("True" if is_sorted_descending(head) else "False")
C#
// C# program to recursively check Linked List 
// is sorted in descending order or not 

using System;

class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

// Recursive function to check if the singly linked list 
// is sorted in descending order
class GfG {
    static bool IsSortedDescending(Node curr) {
      
        // Base case: empty list or single node
        if (curr == null || curr.next == null) {
            return true;
        }

        // If current node's data is less than the next 
		// node's data, list is not sorted
        if (curr.data < curr.next.data) {
            return false;
        }

        // Recursion for the rest of the list
        return IsSortedDescending(curr.next);
    }

    static void PrintList(Node head) {
      	Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
        Console.WriteLine();
    }

    static void Main() {
      
        // singly linked list 10->8->5->2
        Node head = new Node(10);
        head.next = new Node(8);
        head.next.next = new Node(5);
        head.next.next.next = new Node(2);
		Console.WriteLine(IsSortedDescending(head) ? "True" : "False");
    }
}
JavaScript
// Javascript program to recursively check Linked List
// is sorted in descending order

class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Recursive function to check if the singly linked 
// list is sorted in descending order
function isSortedDescending(curr) {

    // Base case: empty list or single node
    if (curr === null || curr.next === null) {
        return true;
    }
    
    // If current node's data is less than the next 
    // node's data, list is not sorted
    if (curr.data < curr.next.data) {
        return false;
    }
    
    // Recursion for the rest of the list
    return isSortedDescending(curr.next);
}

function printList(head) {
	let curr = head;
    while (curr !== null) {
        console.log(curr.data);
        curr = curr.next;
    }
    console.log();
}

// singly linked list 10->8->5->2
let head = new Node(10);
head.next = new Node(8);
head.next.next = new Node(5);
head.next.next.next = new Node(2);

console.log(isSortedDescending(head) ? "True" : "False");

Output
True

Time complexity: O(n), where n are the number of nodes in the linked list.
Auxiliary Space: O(n)

[Expected Approach – 2] Using Iterative MethodO(n) Time and O(1) Space:

The idea is to traverse the linked list from head node till the end, checking if each node’s data is greater than the next node’s data. If the condition fails , return false . If all nodes satisfy the condition return true.

Below is the implementation of above approach:

C++
// C++ program to check Linked List is sorted
// in descending order or not

#include <bits/stdc++.h>
using namespace std;

class Node {
  public:
    int data;
    Node *next;

    Node(int x) {
        data = x;
        next = NULL;
    }
};

// Function to check if the singly linked list is
// sorted in descending order
bool isSortedDescending(Node *head) {
    Node *curr = head;
    while (curr != NULL && curr->next != NULL) {

        // If current node's data is less than the next
        // node's data, list is not sorted in descending order
        if (curr->data < curr->next->data) {
            return false;
        }
        curr = curr->next;
    }
    return true;
}

void printList(Node *node) {
    Node *curr = node;
    while (curr != NULL) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {
  
    // singly linked list 10->8->5->2
    Node *head = new Node(10);
    head->next = new Node(8);
    head->next->next = new Node(5);
    head->next->next->next = new Node(2);

    if (isSortedDescending(head)) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }

    return 0;
}
C
// C program to check Linked List
// is sorted in descending order or not

#include <stdio.h>
#include <stdlib.h> 
#include <stdbool.h>

struct Node {
    int data;
    struct Node *next;
};

// Function to check if the singly linked list is 
// sorted in descending order
bool isSortedDescending(struct Node *head) {
    struct Node *curr = head;
    while (curr != NULL && curr->next != NULL) {
      
        // If current node's data is less than the next 
        // node's data, list is not sorted in descending order
        if (curr->data < curr->next->data) {
            return false;
        }
        curr = curr->next;
    }
  
    // List is sorted in descending order
    return true; 
}

void printList(struct Node *node) {
    struct Node *curr = node;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("\n");
}

struct Node *createNode(int x) {
    struct Node *newNode = 
      	(struct Node *)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->next = NULL;
    return newNode;
}

int main() {
  
    // singly linked list 10->8->5->2
    struct Node *head = createNode(10);
    head->next = createNode(8);
    head->next->next = createNode(5);
    head->next->next->next = createNode(2);

    if (isSortedDescending(head)) {
        printf("True\n");
    }
    else {
        printf("False\n");
    }

    return 0;
}
Java
// Java program to check Linked List is sorted
// in descending order or not

class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

// Function to check if the singly linked list is sorted
// in descending order
class GfG {
    static boolean isSortedDescending(Node head) {
        Node curr = head;
        while (curr != null && curr.next != null) {
          
            // If current node's data is less than the next 
            // node's data, list is not sorted in descending order
            if (curr.data < curr.next.data) {
                return false;
            }
            curr = curr.next;
        }
      
        // List is sorted in descending order
        return true; 
    }

    static void printList(Node node) {
        Node curr = node;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
      
        // singly linked list 10->8->5->2
        Node head = new Node(10);
        head.next = new Node(8);
        head.next.next = new Node(5);
        head.next.next.next = new Node(2);

        if (isSortedDescending(head)) {
            System.out.println("True");
        }
        else {
            System.out.println("False");
        }
    }
}
Python
# Python3 program to check Linked List is sorted
# in descending order or not

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to check if the singly linked list is 
# sorted in descending order
def is_sorted_descending(head):
    curr = head
    while curr and curr.next:
      
        # If current node's data is less than the next
        # node's data, list is not sorted
        if curr.data < curr.next.data:
            return False
        curr = curr.next

    # List is sorted in descending order
    return True

def printList(node):
    curr = node
    while curr:
        print(curr.data, end=" ")
        curr = curr.next
    print()


if __name__ == "__main__":
  
    # singly linked list 10->8->5->2
    head = Node(10)
    head.next = Node(8)
    head.next.next = Node(5)
    head.next.next.next = Node(2)

    if is_sorted_descending(head):
        print("True")
    else:
        print("False")
C#
// C# program to check Linked List is sorted
// in descending order or not

using System;

class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

// Function to check if the singly linked list
// is sorted in descending order
class GfG {
    static bool IsSortedDescending(Node head) {
        Node curr = head;
        while (curr != null && curr.next != null) {

            // If current node's data is less than the next
            // node's data, list is not sorted in descending
            // order
            if (curr.data < curr.next.data) {
                return false;
            }
            curr = curr.next;
        }

        // List is sorted in descending order
        return true;
    }

    static void PrintList(Node node) {
        Node curr = node;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
        Console.WriteLine();
    }

    static void Main(string[] args) {
      
        // singly linked list 10->8->5->2
        Node head = new Node(10);
        head.next = new Node(8);
        head.next.next = new Node(5);
        head.next.next.next = new Node(2);

        if (IsSortedDescending(head)) {
            Console.WriteLine("True");
        }
        else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to check Linked List
// is sorted in descending order or not

class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Function to check if the singly linked list
// is sorted in descending order
function isSortedDescending(head) {
    let curr = head;
    while (curr !== null && curr.next !== null) {

        // If current node's data is less than
        // the next node's data, list is not sorted
        if (curr.data < curr.next.data) {
            return false;
        }
        curr = curr.next;
    }

    // List is sorted in descending order
    return true;
}

function printList(node) {
    let curr = node;
    while (curr !== null) {
        console.log(curr.data);
        curr = curr.next;
    }
}

// singly linked list 10->8->5->2
let head = new Node(10);
head.next = new Node(8);
head.next.next = new Node(5);
head.next.next.next = new Node(2);

console.log(isSortedDescending(head) ? "True" : "False");

Output
True

Time Complexity : O(n), where n are the number of nodes in the linked list.
Auxiliary Space: O(1)



Next Article

Similar Reads