Check if a Linked List is Pairwise Sorted

Given a linked list. The task is to check if the linked list is pairwise sorted or not.

A Linked List is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. In the case of odd number of nodes, the last node is ignored and the result is based on remaining even number of nodes.

Examples:

Input: List =  10 -> 15 -> 9 -> 9 -> 1 -> 5
Output: YES

Input: List = 10 -> 15 -> 8 -> 9 -> 10 -> 5
Output: NO

Approach: The idea is to traverse the linked list from left to right. Compare nodes pairwise, if any pair violates property, return false. If no pair violates property, return True.

Below is the implementation of above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to check if linked list is
// pairwise sorted
#include <iostream>
  
using namespace std;
  
// A linked list node
struct Node {
    int data;
    struct Node* next;
};
  
// Function to check if linked list is
// pairwise sorted
bool isPairWiseSorted(struct Node* head)
{
    bool flag = true;
  
    struct Node* temp = head;
  
    // Traverse further only if there
    // are at-least two nodes left
    while (temp != NULL && temp->next != NULL) {
        if (temp->data > temp->next->data) {
            flag = false;
            break;
        }
  
        temp = temp->next->next;
    }
  
    return flag;
}
  
// Function to add a node at the
// begining of Linked List
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
  
    /* put in the data */
    new_node->data = new_data;
  
    /* link the old list off the new node */
    new_node->next = (*head_ref);
  
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
  
// Driver program to test above function
int main()
{
    struct Node* start = NULL;
  
    /* The constructed linked list is: 
    10->15->9->9->1->5 */
    push(&start, 5);
    push(&start, 1);
    push(&start, 9);
    push(&start, 9);
    push(&start, 15);
    push(&start, 10);
  
    if (isPairWiseSorted(start))
        cout << "YES";
    else
        cout << "NO";
  
    return 0;
}

chevron_right


Output:

YES


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.