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
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Merge Sort for Linked Lists
Next article icon

Sort a Linked List in wave form

Last Updated : 21 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an unsorted Linked List of integers. The task is to sort the Linked List into a wave like Line. A Linked List is said to be sorted in Wave Form if the list after sorting is in the form: 

list[0] >= list[1] <= list[2] >= …..

Where list[i] denotes the data at i-th node of the Linked List.

Examples:  

Input : List = 2 -> 4 -> 6 -> 8 -> 10 -> 20 Output : 4 -> 2 -> 8 -> 6 -> 20 -> 10  Input : List = 3 -> 6 -> 5 -> 10 -> 7 -> 20 Output : 6 -> 3 -> 10 -> 5 -> 20 -> 7

A Simple Solution is to use sorting. First sort the input linked list, then swap all adjacent elements.

For example, let the input list be 3 -> 6 -> 5 -> 10 -> 7 -> 20. After sorting, we get 3 -> 5 -> 6 -> 7 -> 10 -> 20. After swapping adjacent elements, we get 5 -> 3 -> 7 -> 6 -> 20 -> 10 which is the required list in wave form.

Time Complexity: O(N*logN), where N is the number nodes in the list.

Efficient Solution: This can be done in O(n) time by doing a single traversal of the given list. The idea is based on the fact that if we make sure that all even positioned (at index 0, 2, 4, ..) elements are greater than their adjacent odd elements, we don’t need to worry about oddly positioned element. Following are simple steps.

Note: Assuming indexes in list starts from zero. That is, list[0] represents the first elements of the linked list.

Traverse all even positioned elements of input linked list, and do following. 

  • If current element is smaller than previous odd element, swap previous and current.
  • If current element is smaller than next odd element, swap next and current.

Below is the implementation of above approach:  

C++




// C++ program to sort linked list
// in wave form
#include <climits>
#include <iostream>
 
using namespace std;
 
// A linked list node
struct Node {
    int data;
    struct Node* next;
};
 
// 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;
}
 
// Function get size of the list
int listSize(struct Node* node)
{
    int c = 0;
 
    while (node != NULL) {
        c++;
 
        node = node->next;
    }
 
    return c;
}
 
// Function to print the list
void printList(struct Node* node)
{
    while (node != NULL) {
        cout << node->data << " ";
 
        node = node->next;
    }
}
 
/* UTILITY FUNCTIONS */
/* Function to swap two integers */
void swap(int* a, int* b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
 
// Function to sort linked list in
// wave form
void sortInWave(struct Node* head)
{
    struct Node* current = head;
    struct Node* prev = NULL;
 
    // Variable to track even position
    int i = 0;
 
    // Size of list
    int n = listSize(head);
 
    // Traverse all even positioned nodes
    while (i < n) {
 
        if (i % 2 == 0) {
            // If current even element is
            // smaller than previous
            if (i > 0 && (prev->data > current->data))
                swap(&(current->data), &(prev->data));
 
            // If current even element is
            // smaller than next
            if (i < n - 1 && (current->data < current->next->data))
                swap(&(current->data), &(current->next->data));
        }
 
        i++;
 
        prev = current;
        current = current->next;
    }
}
 
// Driver program to test above function
int main()
{
    struct Node* start = NULL;
 
    /* The constructed linked list is:
    10, 90, 49, 2, 1, 5, 23*/
    push(&start, 23);
    push(&start, 5);
    push(&start, 1);
    push(&start, 2);
    push(&start, 49);
    push(&start, 90);
    push(&start, 10);
 
    sortInWave(start);
 
    printList(start);
 
    return 0;
}
 
 

Java




// Java program to sort linked list
// in wave form
class GFG
{
     
// A linked list node
static class Node
{
    int data;
    Node next;
};
 
// Function to add a node at the
// beginning of Linked List
static Node 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;
    return head_ref;
}
 
// Function get size of the list
static int listSize( Node node)
{
    int c = 0;
    while (node != null)
    {
        c++;
        node = node.next;
    }
    return c;
}
 
// Function to print the list
static void printList( Node node)
{
    while (node != null)
    {
        System.out.print(node.data + " ");
        node = node.next;
    }
}
 
// Function to sort linked list in
// wave form
static Node sortInWave( Node head)
{
    Node current = head;
    Node prev = null;
 
    // Variable to track even position
    int i = 0;
 
    // Size of list
    int n = listSize(head);
 
    // Traverse all even positioned nodes
    while (i < n)
    {
        if (i % 2 == 0)
        {
            // If current even element is
            // smaller than previous
            if (i > 0 && (prev.data > current.data))
            {
                int t = prev.data;
                prev.data = current.data;
                current.data = t;
            }
                 
            // If current even element is
            // smaller than next
            if (i < n - 1 && (current.data <
                              current.next.data))
            {
                int t = current.next.data;
                current.next.data = current.data;
                current.data = t;
            }
        }
        i++;
 
        prev = current;
        current = current.next;
    }
    return head;
}
 
// Driver Code
public static void main(String args[])
{
    Node start = null;
 
    /* The constructed linked list is:
    10, 90, 49, 2, 1, 5, 23*/
    start = push(start, 23);
    start = push(start, 5);
    start = push(start, 1);
    start = push(start, 2);
    start = push(start, 49);
    start = push(start, 90);
    start = push(start, 10);
 
    start = sortInWave(start);
 
    printList(start);
}
}
 
// This code is contributed by Arnab Kundu
 
 

Python3




# Python3 program to sort linked list
# in wave form
  
# A linked list node
class Node:
     
    def __init__(self):
         
        self.data = 0
        self.next = None
 
# Function to add a node at the
# beginning of Linked List
def push( head_ref, new_data):
 
    ''' allocate node '''
    new_node = 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;
     
    return head_ref
  
# Function get size of the list
def listSize(node):
 
    c = 0;
  
    while (node != None):
        c += 1
  
        node = node.next;
  
    return c;
  
# Function to print the list
def printList(node):
 
    while (node != None):
         
        print(node.data, end = ' ')
  
        node = node.next;
  
# Function to sort linked list in
# wave form
def sortInWave(head):
 
    current = head;
    prev = None;
  
    # Variable to track even position
    i = 0;
  
    # Size of list
    n = listSize(head);
  
    # Traverse all even positioned nodes
    while (i < n):
  
        if (i % 2 == 0):
     
            # If current even element is
            # smaller than previous
            if (i > 0 and (prev.data > current.data)):
                (current.data), (prev.data) = (prev.data), (current.data)
  
            # If current even element is
            # smaller than next
            if (i < n - 1 and (current.data < current.next.data)):
                (current.data), (current.next.data) = (current.next.data), (current.data)
  
        i += 1
  
        prev = current;
        current = current.next;
      
# Driver program to test above function
if __name__=='__main__':
     
    start = None;
  
    ''' The constructed linked list is:
    10, 90, 49, 2, 1, 5, 23'''
    start = push(start, 23);
    start = push(start, 5);
    start = push(start, 1);
    start = push(start, 2);
    start = push(start, 49);
    start = push(start, 90);
    start = push(start, 10)
  
    sortInWave(start)
  
    printList(start);
  
# This code is contributed by pratham76
 
 

C#




// C# program to sort linked list
// in wave form
using System;
 
class GFG{
     
// A linked list node
class Node
{
    public int data;
    public Node next;
};
 
// Function to add a node at the
// beginning of Linked List
static Node 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;
    return head_ref;
}
 
// Function get size of the list
static int listSize( Node node)
{
    int c = 0;
     
    while (node != null)
    {
        c++;
        node = node.next;
    }
    return c;
}
 
// Function to print the list
static void printList( Node node)
{
    while (node != null)
    {
        Console.Write(node.data + " ");
        node = node.next;
    }
}
 
// Function to sort linked list in
// wave form
static Node sortInWave( Node head)
{
    Node current = head;
    Node prev = null;
 
    // Variable to track even position
    int i = 0;
 
    // Size of list
    int n = listSize(head);
 
    // Traverse all even positioned nodes
    while (i < n)
    {
        if (i % 2 == 0)
        {
             
            // If current even element is
            // smaller than previous
            if (i > 0 && (prev.data >
                          current.data))
            {
                int t = prev.data;
                prev.data = current.data;
                current.data = t;
            }
                 
            // If current even element is
            // smaller than next
            if (i < n - 1 && (current.data <
                              current.next.data))
            {
                int t = current.next.data;
                current.next.data = current.data;
                current.data = t;
            }
        }
        i++;
 
        prev = current;
        current = current.next;
    }
    return head;
}
 
// Driver Code
public static void Main(string []args)
{
    Node start = null;
 
    // The constructed linked list is:
    // 10, 90, 49, 2, 1, 5, 23
    start = push(start, 23);
    start = push(start, 5);
    start = push(start, 1);
    start = push(start, 2);
    start = push(start, 49);
    start = push(start, 90);
    start = push(start, 10);
 
    start = sortInWave(start);
 
    printList(start);
}
}
 
// This code is contributed by rutvik_56
 
 

Javascript




<script>
 
      // JavaScript program to sort linked list
      // in wave form
      // A linked list node
      class Node {
        constructor() {
          this.data = 0;
          this.next = null;
        }
      }
 
      // 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;
        return head_ref;
      }
 
      // Function get size of the list
      function listSize(node) {
        var c = 0;
 
        while (node != null) {
          c++;
          node = node.next;
        }
        return c;
      }
 
      // Function to print the list
      function printList(node) {
        while (node != null) {
          document.write(node.data + " ");
          node = node.next;
        }
      }
 
      // Function to sort linked list in
      // wave form
      function sortInWave(head) {
        var current = head;
        var prev = null;
 
        // Variable to track even position
        var i = 0;
 
        // Size of list
        var n = listSize(head);
 
        // Traverse all even positioned nodes
        while (i < n) {
          if (i % 2 == 0) {
            // If current even element is
            // smaller than previous
            if (i > 0 && prev.data > current.data) {
              var t = prev.data;
              prev.data = current.data;
              current.data = t;
            }
 
            // If current even element is
            // smaller than next
            if (i < n - 1 && current.data < current.next.data) {
              var t = current.next.data;
              current.next.data = current.data;
              current.data = t;
            }
          }
          i++;
 
          prev = current;
          current = current.next;
        }
        return head;
      }
 
      // Driver Code
      var start = null;
 
      // The constructed linked list is:
      // 10, 90, 49, 2, 1, 5, 23
      start = push(start, 23);
      start = push(start, 5);
      start = push(start, 1);
      start = push(start, 2);
      start = push(start, 49);
      start = push(start, 90);
      start = push(start, 10);
 
      start = sortInWave(start);
 
      printList(start);
       
</script>
 
 
Output
90 10 49 1 5 2 23 


Next Article
Merge Sort for Linked Lists

B

barykrg
Improve
Article Tags :
  • DSA
  • Linked List
  • Data Structures-Linked List
  • Linked-List-Sorting
Practice Tags :
  • Linked List

Similar Reads

  • 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
  • Insertion Sort for Doubly Linked List
    Given a doubly linked list, the task is to sort the doubly linked list in non-decreasing order using the insertion sort. Examples: Input: head: 5<->3<->4<->1<->2Output: 1<->2<->3<->4<->5Explanation: Doubly Linked List after sorting using insertion sort
    10 min read
  • Merge Sort for Linked Lists
    Given a singly linked list, The task is to sort the linked list in non-decreasing order using merge sort. Examples: Input: 40 -> 20 -> 60 -> 10 -> 50 -> 30 -> NULLOutput: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> NULL Input: 9 -> 5 -> 2 -> 8 -> NULLOutput: 2
    12 min read
  • Insertion Sort for Singly Linked List
    Given a singly linked list, the task is to sort the list (in ascending order) using the insertion sort algorithm. Examples: Input: 5->4->1->3->2Output: 1->2->3->4->5Input: 4->3->2->1Output: 1->2->3->4 The prerequisite is Insertion Sort on Array. The idea is
    8 min read
  • Second Smallest Element in a Linked List
    Given a Linked list of integer data. The task is to write a program that efficiently finds the second smallest element present in the Linked List. Examples: Input : List = 12 -> 35 -> 1 -> 10 -> 34 -> 1Output : The second smallest element is 10.Input : List = 10 -> 5 -> 10Output
    15+ min read
  • Sort an array in wave form
    Given an unsorted array of integers, sort the array into a wave array. An array arr[0..n-1] is sorted in wave form if: arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ..... Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80}Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} Explanation: here yo
    10 min read
  • Flattening a linked list | Set 2
    Given a linked list where every node represents a linked list and contains two pointers of its type: Pointer to next node in the main list (we call it ‘right’ pointer in the below code)Pointer to a linked list where this node is head (we call it ‘down’ pointer in the below code).All linked lists are
    13 min read
  • Merge Sort for Doubly Linked List
    Given a doubly linked list, The task is to sort the doubly linked list in non-decreasing order using merge sort.Examples: Input: 10 <-> 8 <-> 4 <-> 2Output: 2 <-> 4 <-> 8 <-> 10Input: 5 <-> 3 <-> 2Output: 2 <-> 3 <-> 5 Note: Merge sort for
    13 min read
  • Iterative Merge Sort for Linked List
    Given a singly linked list of integers, the task is to sort it using iterative merge sort. Examples: Input: 40 -> 20 -> 60 -> 10 -> 50 -> 30 -> NULLOutput: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> NULL Input: 9 -> 5 -> 2 -> 8 -> NULLOutput: 2 -> 5 ->
    14 min read
  • Linked List Notes for GATE Exam [2024]
    The "Linked List Notes for GATE Exam" is a comprehensive resource designed to aid students in preparing for the Graduate Aptitude Test in Engineering (GATE). Focused specifically on linked lists, a fundamental data structure in computer science, these notes offer a detailed and structured approach t
    15+ 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