Sort a Linked List in wave form
Last Updated :
21 Nov, 2022
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>
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem