×

Partitioning a linked list around a given value

Partitioning a linked list around a given value

In this problem, we are given a linked list and a value k. We need to partition the given linked list so that all nodes less than k come first, then all nodes that are equal to k, and finally nodes that are greater than k. Also, we need to preserve the order of nodes same as the original list.

Example:

          Input:

2 -> 4 -> 5 -> 4 -> 3 -> 2 -> 3                     k = 3

Output:

2 -> 2 -> 3 -> 3 -> 4 -> 5 -> 4

Input:

1 -> 3 -> 2 -> 5 -> 3 -> 6                            k = 4

Output:

1 -> 3 -> 2 -> 3 -> 5 -> 6        

Method:

In this method, we will take three list and initialize their first and last nodes as given below:        

  • The linked list contains the node which has a smaller value than k.
  • The linked list contains the node which has an equal value to k.
  • The linked list contains the node which has a greater value than k.

After this, we traverse the given linked list. If a node has a smaller value than k, we will append that node at the end of the smaller linked list. If the node value is equal to k, we will append it at the end of the equal linked list, and if a value is greater than k, we will append that node at the end of the greater linked list. Finally, we will concatenate these three linked lists to display the output. 

C Program to partitioning a linked list around a given value:

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start = NULL;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node * t, * p;
 t = (struct node *)malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start -> info = item;
 start -> next = NULL;
 return;
 }
 else
 {
 struct node * p = start;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // For partitioning a linked list around a given value
 struct node * partition(struct node * temp, int k)
 {
             struct node * smallerFirst = NULL, * smallerLast = NULL;
     struct node * equalFirst = NULL, * equalLast = NULL;
     struct node * greaterFirst = NULL, * greaterLast = NULL;
             while(temp != NULL)
             {
                  if(temp -> info < k)
                 {
                         if(smallerFirst == NULL)
                         {
                                     smallerFirst = temp;
                                     smallerLast =  smallerFirst;
                         }
                         else
                         {
                                     smallerLast -> next = temp;
                                     smallerLast = smallerLast -> next;
                         }
                 }
                else if( temp -> info == k)
        {
         if(equalFirst == NULL)
                         {
                                     equalFirst = temp;
                                     equalLast =  equalFirst;
                         }
                         else
                         {
                                     equalLast -> next = temp;
                                     equalLast = equalLast -> next;
                         }
                }
         else
         {
            if(greaterFirst == NULL)
                            {
                                       greaterFirst = temp;
                                       greaterLast =  greaterFirst;
                            }
                            else
                            {
                                     greaterLast -> next = temp;
                                     greaterLast = greaterLast -> next;
                            }
                 }
         temp = temp -> next;
     }
     // For fixing the end of greater linked list
     if(greaterLast != NULL)
         greaterLast -> next = NULL;
     // Connect three lists
     // If smaller list is empty
        if (smallerFirst == NULL)
       {
            if (equalFirst == NULL)
                   return greaterFirst;
            equalLast -> next = greaterFirst;
            return equalFirst;
       }
     // If smaller list is not empty
     // and equal list is empty
     if (equalFirst == NULL)
     {
         smallerLast -> next = greaterFirst;
         return smallerFirst;
     }
     // If both smaller and equal list
     // are non-empty
     smallerLast -> next = equalFirst;
     equalLast -> next = greaterFirst;
     return smallerFirst;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t -> next != NULL)
                                     {
                         printf("%d -> ",t -> info);
                         t = t -> next;
                         }
                         printf("%d\n",t -> info);
 }
 // Driver Function
 int main()
 {
     int k;
     printf("Enter the value of k:");
     scanf("%d",&k);
     add(2);
     add(4);
     add(5);
     add(4);
     add(3);
     add(2);
     add(3);
     printf("Given Linked List: \n");
     traverse(start);
     start = partition(start, k);
     printf("Linked List After partitioning: \n");
     traverse(start);
     return 0;
 } 

Output:

Partitioning a linked list around a given value


Related Topics

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

How to Start Learning DSA

All programmer experiences a point along the way where they wish they could approach a problem in a more effective manner. They finally learn about the terminology DSA while trying...

10 minutes read.

Applications of trees in data structures

Data structures Storage used to organize and store data is known as the data structure. It is a method of managing computerized data to translate or retrieve it more efficiently. A...

7 minutes read.

Invert binary tree

Invert binary tree is a mirror image of a tree. It is pretty much the same compared to the only difference: its left and right children are swapped with the...

4 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Tree terminology in Data structures

Data structures The storage used to organize and store data is known as a data structure, and it is a method where data can be arranged on a computer to be...

6 minutes read.

Recaman’s Sequence

Recamán's succession repeat connection in arithmetic and software engineering. Since its components are obviously connected with the past components, they are as often as possible characterized utilizing recursion. It takes its...

4 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Arrange consonants and vowels nodes in a linked list

Arrange consonants and vowels nodes in a linked list In this problem, we have given a singly linked list. Here we will arrange the consonants and vowels nodes of the list...

2 minutes read.

FIFO approach

FIFO is first in first out approach. It is done for the list of elements in data structures where first element will be deleted after another element ia added to it Here,...

6 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Convert Sorted List to Binary Search Tree

Implementation // creating the C++ implementation of the following approach: - #include <bits/stdc++.h> using namespace std; /* Create the link list node and see its implementation. */ class L__Nod { public: int record; L__Nod* next; }; /* constructing a new binary...

15 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

3 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Insertion sort

Insertion sort is a simple sorting technique. It is best suited for small data sets, but it does not suitable for large data sets. In this technique, we pick an...

4 minutes read.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.