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