Check if linked list is sorted (Iterative and Recursive)

08 Nov, 2021
Given a Linked List, task is to check whether the Linked List is sorted in Descending order or not? 
Examples :  
Input  : 8 -> 7 -> 5 -> 2 -> 1
Output : Yes
Explanation :
In given linked list, starting from head,
8 > 7 > 5 > 2 > 1. So, it is sorted in reverse order

Input  : 24 -> 12 -> 9 -> 11 -> 8 -> 2
Output : No
Iterative Approach : Traverse the linked list from head to end. For every newly encountered element, check node -> data > node -> next -> data. If True, do same for each node else return 0 and Print “No”.  
C++
Java
Python3
C#
Javascript
// C++ program to check Linked List is sorted// in descending order or not#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node{    int data;    struct Node* next;}; // function to Check Linked List is// sorted in descending order or notbool isSortedDesc(struct Node *head){    if (head == NULL)        return true;     // Traverse the list till last node and return    // false if a node is smaller than or equal    // its next.    for (Node *t=head; t->next != NULL; t=t->next)       if (t->data <= t->next->data)            return false;    return true;} Node *newNode(int data){   Node *temp = new Node;   temp->next = NULL;   temp->data = data;} // Driver program to test aboveint main(){    struct Node *head = newNode(7);    head->next = newNode(5);    head->next->next = newNode(4);    head->next->next->next = newNode(3);            isSortedDesc(head) ? cout << "Yes" :                         cout << "No";         return 0;}
// Java program to check Linked List is sorted// in descending order or notclass GFG{ /* Linked list node */static class Node{    int data;    Node next;}; // function to Check Linked List is// sorted in descending order or notstatic boolean isSortedDesc(Node head){    if (head == null)        return true;     // Traverse the list till last node and return    // false if a node is smaller than or equal    // its next.    for (Node t = head; t.next != null; t = t.next)    if (t.data <= t.next.data)            return false;    return true;} static Node newNode(int data){    Node temp = new Node();    temp.next = null;    temp.data = data;    return temp;} // Driver Codepublic static void main(String[] args){    Node head = newNode(7);    head.next = newNode(5);    head.next.next = newNode(4);    head.next.next.next = newNode(3);             if(isSortedDesc(head))        System.out.println("Yes");    else        System.out.println("No");}} // This code is contributed by 29AjayKumar
# Python3 program to check Linked List is sorted# in descending order or not''' Linked list Node ''' class Node:    def __init__(self, data):        self.data = data;        self.next = next; # function to Check Linked List is# sorted in descending order or notdef isSortedDesc(head):    if (head == None):        return True;     # Traverse the list till last Node and return    # False if a Node is smaller than or equal    # its next.    while(head.next != None):        t = head;        if (t.data <= t.next.data):            return False;        head = head.next    return True; def newNode(data):    temp = Node(0);    temp.next = None;    temp.data = data;    return temp; # Driver Codeif __name__ == '__main__':    head = newNode(7);    head.next = newNode(5);    head.next.next = newNode(4);    head.next.next.next = newNode(3);     if (isSortedDesc(head)):        print("Yes");    else:        print("No"); # This code is contributed by 29AjayKumar
// C# program to check Linked List is sorted// in descending order or notusing System;     class GFG{ /* Linked list node */public class Node{    public int data;    public Node next;}; // function to Check Linked List is// sorted in descending order or notstatic bool isSortedDesc(Node head){    if (head == null)        return true;     // Traverse the list till last node and    // return false if a node is smaller than    // or equal to its next.    for (Node t = head;              t.next != null; t = t.next)    if (t.data <= t.next.data)            return false;    return true;} static Node newNode(int data){    Node temp = new Node();    temp.next = null;    temp.data = data;    return temp;} // Driver Codepublic static void Main(String[] args){    Node head = newNode(7);    head.next = newNode(5);    head.next.next = newNode(4);    head.next.next.next = newNode(3);             if(isSortedDesc(head))        Console.WriteLine("Yes");    else        Console.WriteLine("No");}} // This code is contributed by Rajput-Ji
<script>       // JavaScript program to recursively check Linked List      // is sorted in descending order or not      /* Linked list node */      class Node {        constructor() {          this.data = 0;          this.next = null;        }      }       // function to Check Linked List is      // sorted in descending order or not      function isSortedDesc(head) {        // Base cases        if (head == null || head.next == null) return true;         // Check first two nodes and recursively        // check remaining.        return head.data > head.next.data && isSortedDesc(head.next);      }       function newNode(data) {        var temp = new Node();        temp.next = null;        temp.data = data;        return temp;      }       // Driver code      var head = newNode(7);      head.next = newNode(5);      head.next.next = newNode(4);      head.next.next.next = newNode(3);       if (isSortedDesc(head) == true) document.write("Yes");      else document.write("No");       </script>
Yes
 
Time Complexity : O(N), where N is the length of linked list.
Recursive Approach : Check Recursively that node -> data > node -> next -> data, If not, return 0 that is our terminated condition to come out from recursion else Call Check_List Function Recursively for next node. 
C++
Java
Python3
C#
Javascript
// C++ program to recursively check Linked List// is sorted in descending order or not#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node{    int data;    struct Node* next;}; // function to Check Linked List is// sorted in descending order or notbool isSortedDesc(struct Node *head){    // Base cases    if (head == NULL || head->next == NULL)        return true;         // Check first two nodes and recursively    // check remaining.      return (head->data > head->next->data &&        isSortedDesc(head->next));} Node *newNode(int data){   Node *temp = new Node;   temp->next = NULL;   temp->data = data;} // Driver program to test aboveint main(){    struct Node *head = newNode(7);    head->next = newNode(5);    head->next->next = newNode(4);    head->next->next->next = newNode(3);            isSortedDesc(head) ? cout << "Yes" :                         cout << "No";         return 0;}
// Java program to recursively check Linked List// is sorted in descending order or notclass GfG { /* Linked list node */static class Node{    int data;    Node next;} // function to Check Linked List is// sorted in descending order or notstatic boolean isSortedDesc(Node head){    // Base cases    if (head == null || head.next == null)        return true;         // Check first two nodes and recursively    // check remaining.    return (head.data > head.next.data && isSortedDesc(head.next));} static Node newNode(int data){Node temp = new Node();temp.next = null;temp.data = data;return temp;} // Driver program to test abovepublic static void main(String[] args){    Node head = newNode(7);    head.next = newNode(5);    head.next.next = newNode(4);    head.next.next.next = newNode(3);             if(isSortedDesc(head) == true)    System.out.println("Yes");    else    System.out.println("No");     }}
# Python3 program to recursively check# Linked List is sorted in descending# order or not  # Linked list nodeclass Node:         def __init__(self, data):                 self.data = data        self.next = None # Function to Check Linked List is# sorted in descending order or notdef isSortedDesc(head):         # Base cases    if (head == None or head.next == None):        return True          # Check first two nodes and recursively    # check remaining.      return (head.data > head.next.data and           isSortedDesc(head.next)) def newNode(data):    temp = Node(data)   return temp    # Driver codeif __name__=="__main__":         head = newNode(7)    head.next = newNode(5)    head.next.next = newNode(4)    head.next.next.next = newNode(3)             if isSortedDesc(head):        print("Yes")    else:        print("No") # This code is contributed by rutvik_56
// C# program to recursively check Linked List// is sorted in descending order or notusing System; class GfG{ /* Linked list node */public class Node{    public int data;    public Node next;} // function to Check Linked List is// sorted in descending order or notstatic bool isSortedDesc(Node head){    // Base cases    if (head == null || head.next == null)        return true;         // Check first two nodes and recursively    // check remaining.    return (head.data > head.next.data &&                    isSortedDesc(head.next));} static Node newNode(int data){    Node temp = new Node();    temp.next = null;    temp.data = data;    return temp;} // Driver codepublic static void Main(String[] args){    Node head = newNode(7);    head.next = newNode(5);    head.next.next = newNode(4);    head.next.next.next = newNode(3);             if(isSortedDesc(head) == true)    Console.WriteLine("Yes");    else    Console.WriteLine("No");     }} // This code contributed by Rajput-Ji
<script>    // Javascript program to recursively check Linked List    // is sorted in descending order or not    class Node    {        constructor(data) {           this.next = null;           this.data = data;        }    }         // function to Check Linked List is    // sorted in descending order or not    function isSortedDesc(head)    {        // Base cases        if (head == null || head.next == null)            return true;         // Check first two nodes and recursively        // check remaining.        return (head.data > head.next.data &&                        isSortedDesc(head.next));    }     function newNode(data)    {        let temp = new Node(data);        return temp;    }         let head = newNode(7);    head.next = newNode(5);    head.next.next = newNode(4);    head.next.next.next = newNode(3);              if(isSortedDesc(head) == true)        document.write("Yes");    else        document.write("No");         // This code is contributed by divyeshrabadiya07.</script>
Yes
 
prerna saini
Rajput-Ji
29AjayKumar
rutvik_56
rdtank
divyeshrabadiya07
Linked-List-Sorting
C++
Linked List
Recursion
Sorting
Technical Scripter
Linked List
Recursion
Sorting
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)