Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Check if a linked list is Circular Linked List
Next article icon

Check if a Linked List is Pairwise Sorted

Last Updated : 22 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 the 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: 

C++
// 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 // beginning 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 of 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; } 
Java
// Java program to check if linked list is  // pairwise sorted  class GFG {   // A linked list node  static class Node {      int data;      Node next;  };  static Node start;  // Function to check if linked list is  // pairwise sorted  static boolean isPairWiseSorted(Node head)  {      boolean flag = true;       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  // beginning of Linked List  static void push(Node head_ref, int new_data)  {           /* allocate node */     Node new_node = new Node();       /* put in the data */     new_node.data = new_data;       /* link the old list of the new node */     new_node.next = head_ref;       /* move the head to point to the new node */     head_ref = new_node;          start = head_ref; }   // Driver Code public static void main(String[] args)  {     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))          System.out.println("YES");     else         System.out.println("NO");     } }  // This code is contributed by PrinciRaj1992  
Python
# Python program to check if linked list is  # pairwise sorted   # Linked List node  class Node:      def __init__(self, data):          self.data = data          self.next = None          start = None  # Function to check if linked list is  # pairwise sorted  def isPairWiseSorted(head) :      flag = True      temp = head       # Traverse further only if there      # are at-least two nodes left      while (temp != None and temp.next != None) :              if (temp.data > temp.next.data) :             flag = False             break                  temp = temp.next.next          return flag   # Function to add a node at the  # beginning of Linked List  def push(head_ref, new_data) :      global start     # allocate node      new_node = Node(0)       # put in the data      new_node.data = new_data       # link the old list of the new node      new_node.next = head_ref       # move the head to point to the new node      head_ref = new_node      start = head_ref  # Driver Code start = None  # 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)) :     print("YES") else:     print("NO")      # This code is contributed by Arnab Kundu 
C#
// C# program to check if linked list is  // pairwise sorted  using System; class GFG {   // A linked list node  public class Node {      public int data;      public Node next;  };  static Node start;  // Function to check if linked list is  // pairwise sorted  static Boolean isPairWiseSorted(Node head)  {      Boolean flag = true;       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  // beginning of Linked List  static void push(Node head_ref, int new_data)  {           /* allocate node */     Node new_node = new Node();       /* put in the data */     new_node.data = new_data;       /* link the old list of the new node */     new_node.next = head_ref;       /* move the head to point to the new node */     head_ref = new_node;      start = head_ref; }   // Driver Code public static void Main(String[] args)  {     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))          Console.WriteLine("YES");     else         Console.WriteLine("NO");     } }  // This code is contributed by Rajput-Jiv 
JavaScript
<script>        // JavaScript program to check if linked list is       // pairwise sorted       // A linked list node       class Node {         constructor() {           this.data = 0;           this.next = null;         }       }       var start = null;        // Function to check if linked list is       // pairwise sorted       function isPairWiseSorted(head) {         var flag = true;          var 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       // beginning of Linked List       function push(head_ref, new_data) {         /* allocate node */         var new_node = new Node();          /* put in the data */         new_node.data = new_data;          /* link the old list of the new node */         new_node.next = head_ref;          /* move the head to point to the new node */         head_ref = new_node;         start = head_ref;       }        // Driver Code       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)) document.write("YES");       else document.write("NO");        </script> 

Output
YES

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(1)

Next Article
Check if a linked list is Circular Linked List

B

barykrg
Improve
Article Tags :
  • Misc
  • Linked List
  • Sorting
  • DSA
Practice Tags :
  • Linked List
  • Misc
  • Sorting

Similar Reads

  • Check if a linked list is sorted in non-increasing order
    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 -> 1Output: YesInput : 24 -> 12 -> 9 -> 11 -> 8 -> 2Output: No [Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space:The
    12 min read
  • Check if a given array is pairwise sorted or not
    An array is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. In case of odd elements, last element is ignored and result is based on remaining even number of elements. Examples: Input : arr[] = {10, 15, 9, 9, 1, 5}; Output : Yes Pairs are (10, 15), (
    5 min read
  • Check if elements of Linked List are present in pair
    Given a singly linked list of integers. The task is to check if each element in the linked list is present in a pair i.e. all elements occur even no. of times. Examples: Input: 1 -> 2 -> 3 -> 3 -> 1 -> 2Output: YesInput: 10 -> 20 -> 30 -> 20Output: No Method : Using MapWe wil
    5 min read
  • Merge K sorted linked lists
    Given k sorted linked lists of different sizes, the task is to merge them all maintaining their sorted order. Examples: Input: Output: Merged lists in a sorted order where every element is greater than the previous element. Input: Output: Merged lists in a sorted order where every element is greater
    15+ min read
  • Check if a linked list is Circular Linked List
    Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node. Note: The linked list does not contain any internal loops. Example: Input: LinkedList: 2->4->6->7->5 Outpu
    12 min read
  • Remove duplicates from a sorted linked list
    Given a linked list sorted in non-decreasing order. Return the list by deleting the duplicate nodes from the list. The returned list should also be in non-decreasing order. Example: Input : Linked List = 11->11->11->21->43->43->60Output : 11->21->43->60Explanation: Input :
    15+ min read
  • Check if a pair with given product exists in Linked list
    Given a linked list, and a product K. The task is to check if there exist two numbers in the linked list whose product is equal to the given number K. If there exist two numbers, print them. If there are multiple answers, print any of them. Examples: Input : List = 1 -> 2 -> 3 -> 4 -> 5
    13 min read
  • Sorted insert for circular linked list
    Given a sorted Circular Linked List. The task is to insert the given data in a sorted way. Examples: Input: Output: Explanation: 8 is inserted after 7 and before 9 to preserve the sorted order. Input: Output: Explanation: 1 will be inserted at the beginning of circular linked list. Approach: To inse
    10 min read
  • Finding Median in a Sorted Linked List
    Given A sorted linked list of [Tex]N [/Tex]elements. The task is to find the median in the given Sorted Linked List.We know that median in a sorted array is the middle element. Procedure to find median of N sorted numbers: if N is odd: median is N/2th elementelse median is N/2th element + (N/2+1)th
    14 min read
  • Check linked list with a loop is palindrome or not
    Given a linked list with a loop, the task is to find whether it is palindrome or not. You are not allowed to remove the loop. Examples: Input : 1 -> 2 -> 3 -> 2 /|\ \|/ ------- 1 Output: Palindrome Linked list is 1 2 3 2 1 which is a palindrome. Input : 1 -> 2 -> 3 -> 4 /|\ \|/ ---
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences