×

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

Collision Resolution Techniques

Collision Resolution Techniques Collision in hashing In this, the hash function is used to compute the index of the array.The hash value is used to store the key in the hash table,...

2 minutes read.

Given a Binary Tree, Check if it's balanced

Implementation /*Creating a C++ program that will help us identify whether the given tree is height-balanced or not.  */ #include <bits/stdc++.h> using namespace std; /* A particular binary tree node consists of data with some...

4 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

What is the difference between Tree and Graph

We usually use a diverse range of data structure to store our data and information. To store them in a more sequential manner and to access them easily, we use...

4 minutes read.

Heap Data Structure

In this article, we will learn in detail about Heap (Min heap and Max heap). Before going to the main topics, let’s have a look at what is complete binary...

19 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

Digital Search Tree in Data Structures

What is a digital search Tree in Data Structures? The Digital search tree is known for its application and diversity in the way it has impacted our world in the field...

3 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Merge Conflicts and ways to handle them

Merge Conflicts Whenever dealing with the Git merge operations, conflicts will be the frequently occurred. When more than two developers work on the same file on different systems using Git, they...

4 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.

Dijkstra’s vs Bellman-Ford Algorithm

The Dijkstra Algorithm One of the SSSP (Single Source Shortest Path) algorithms is Dijkstra's. As a result, it finds the shortest path between a source node and all other nodes in...

7 minutes read.

Find out the area between two concentric circles

You have given two values of the radius of two circles. You have to find out the area between these two circles. Let's take an example - For the above diagram,...

3 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

19 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

5 minutes read.