Open In App

Partitioning a linked list around a given value and keeping the original order

Last Updated : 04 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than x. The original relative order of the nodes in each of the three partitions should be preserved.

Examples: 

Input : 1 -> 4 -> 3 -> 2 -> 5 -> 2 -> 3, x = 3
Output: 1 -> 2 -> 2 -> 3 -> 3 -> 4 -> 5
Explanation: In the below linked list, all nodes with value less than 3 are on the left and rest of the nodes on the right by maintaining the relative order.

2_1

Input: 10 -> 4 -> 20 -> 10 -> 3, x = 3
Output: 3 -> 10 -> 4 -> 20 -> 10

Approach:

The idea is to use three dummy nodes to create three separate partitions: less, equal, and greater. As the list is traversed, each node is added to its corresponding partition. Once all nodes are processed, the partitions are connected to form the final list.

C++
// C++ program to partition a linked list
// around a given value.

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int val) {
        data = val;
        next = NULL;
    }
};

Node* partition(Node* head, int x) {
    // Dummy head for nodes less than x
    Node* lessHead = new Node(0); 
    
    // Dummy head for nodes equal to x
    Node* equalHead = new Node(0); 
    
    // Dummy head for nodes greater than or equal to x
    Node* greaterHead = new Node(0);

    Node* less = lessHead;
    Node* equal = equalHead;
    Node* greater = greaterHead;

    Node* curr = head;

    while (curr != NULL) {
        if (curr->data < x) {
            less->next = curr;
            less = less->next;
        } else if (curr->data == x) {
            equal->next = curr;
            equal = equal->next;
        } else {
            greater->next = curr;
            greater = greater->next;
        }
        curr = curr->next;
    }

    // Connect the partitions together
    greater->next = NULL;  
    
    // Connect equal to greater
    equal->next = greaterHead->next; 
    
    // Connect less to equal
    less->next = equalHead->next;  
    
    // New head of the rearranged list
    Node* newHead = lessHead->next; 

    // Clean up dummy nodes
    delete lessHead;
    delete equalHead;
    delete greaterHead;

    return newHead;
}

void printList(Node* head) {
    Node* curr = head;
    while (curr != NULL) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {
    // Creating the linked list: 1 -> 4 -> 3 -> 2 -> 5 -> 2
    Node* head = new Node(1);
    head->next = new Node(4);
    head->next->next = new Node(3);
    head->next->next->next = new Node(2);
    head->next->next->next->next = new Node(5);
    head->next->next->next->next->next = new Node(2);
	
  	int x = 3;
    head = partition(head, x);
    printList(head);

    return 0;
}
C
// C program to partition a linked list
// around a given value.

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

struct Node* createNode(int val);

struct Node* partition(struct Node* head, int x) {
    // Dummy head for nodes less than x
    struct Node* lessHead = createNode(0);

    // Dummy head for nodes equal to x
    struct Node* equalHead = createNode(0);

    // Dummy head for nodes greater than or equal to x
    struct Node* greaterHead = createNode(0);

    struct Node* less = lessHead;
    struct Node* equal = equalHead;
    struct Node* greater = greaterHead;

    struct Node* curr = head;

    while (curr != NULL) {
        if (curr->data < x) {
            less->next = curr;
            less = less->next;
        } else if (curr->data == x) {
            equal->next = curr;
            equal = equal->next;
        } else {
            greater->next = curr;
            greater = greater->next;
        }
        curr = curr->next;
    }

    // Connect the partitions together
    greater->next = NULL;

    // Connect equal to greater
    equal->next = greaterHead->next;

    // Connect less to equal
    less->next = equalHead->next;

    // New head of the rearranged list
    struct Node* newHead = lessHead->next;

    // Clean up dummy nodes
    free(lessHead);
    free(equalHead);
    free(greaterHead);

    return newHead;
}

void printList(struct Node* head) {
    struct Node* curr = head;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("\n");
}

struct Node* createNode(int val) {
    struct Node* newNode = 
      (struct Node*)malloc(sizeof(struct Node));
    newNode->data = val;
    newNode->next = NULL;
    return newNode;
}

int main() {
    // Creating the linked list: 1 -> 4 -> 3 -> 2 -> 5 -> 2
    struct Node* head = createNode(1);
    head->next = createNode(4);
    head->next->next = createNode(3);
    head->next->next->next = createNode(2);
    head->next->next->next->next = createNode(5);
    head->next->next->next->next->next = createNode(2);
	
  	int x = 3;
    head = partition(head, x);
    printList(head);

    return 0;
}
Java
// Java program to partition a linked list
// around a given value.

class Node {
    int data;
    Node next;

    Node(int val) {
        data = val;
        next = null;
    }
}

class GfG {

    static Node partition(Node head, int x) {
        // Dummy head for nodes less than x
        Node lessHead = new Node(0);

        // Dummy head for nodes equal to x
        Node equalHead = new Node(0);

        // Dummy head for nodes greater than or equal to x
        Node greaterHead = new Node(0);

        Node less = lessHead;
        Node equal = equalHead;
        Node greater = greaterHead;

        Node curr = head;

        while (curr != null) {
            if (curr.data < x) {
                less.next = curr;
                less = less.next;
            } else if (curr.data == x) {
                equal.next = curr;
                equal = equal.next;
            } else {
                greater.next = curr;
                greater = greater.next;
            }
            curr = curr.next;
        }

        // Connect the partitions together
        greater.next = null;

        // Connect equal to greater
        equal.next = greaterHead.next;

        // Connect less to equal
        less.next = equalHead.next;

        // New head of the rearranged list
        Node newHead = lessHead.next;

        return newHead;
    }

    static void printList(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // Creating the linked list: 1 -> 4 -> 3 -> 2 -> 5 -> 2
        Node head = new Node(1);
        head.next = new Node(4);
        head.next.next = new Node(3);
        head.next.next.next = new Node(2);
        head.next.next.next.next = new Node(5);
        head.next.next.next.next.next = new Node(2);
		int x = 3;
        head = partition(head, x);
        printList(head);
    }
}
Python
# Python program to partition a linked list
# around a given value.

class Node:
    def __init__(self, val):
        self.data = val
        self.next = None

def partition(head, x):
    # Dummy head for nodes less than x
    lessHead = Node(0)

    # Dummy head for nodes equal to x
    equalHead = Node(0)

    # Dummy head for nodes greater than or equal to x
    greaterHead = Node(0)

    less = lessHead
    equal = equalHead
    greater = greaterHead

    curr = head

    while curr is not None:
        if curr.data < x:
            less.next = curr
            less = less.next
        elif curr.data == x:
            equal.next = curr
            equal = equal.next
        else:
            greater.next = curr
            greater = greater.next
        curr = curr.next

    # Connect the partitions together
    greater.next = None

    # Connect equal to greater
    equal.next = greaterHead.next

    # Connect less to equal
    less.next = equalHead.next

    # New head of the rearranged list
    newHead = lessHead.next

    return newHead

def printList(head):
    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next
    print()

if __name__ == "__main__":
    # Creating the linked list: 1 -> 4 -> 3 -> 2 -> 5 -> 2
    head = Node(1)
    head.next = Node(4)
    head.next.next = Node(3)
    head.next.next.next = Node(2)
    head.next.next.next.next = Node(5)
    head.next.next.next.next.next = Node(2)
    
    x = 3
    head = partition(head, x)
    printList(head)
C#
// C# program to partition a linked list
// around a given value.

using System;

class Node {
    public int data;
    public Node next;

    public Node(int val) {
        data = val;
        next = null;
    }
}

class GfG {

    static Node Partition(Node head, int x) {
        // Dummy head for nodes less than x
        Node lessHead = new Node(0);

        // Dummy head for nodes equal to x
        Node equalHead = new Node(0);

        // Dummy head for nodes greater than or equal to x
        Node greaterHead = new Node(0);

        Node less = lessHead;
        Node equal = equalHead;
        Node greater = greaterHead;

        Node curr = head;

        while (curr != null) {
            if (curr.data < x) {
                less.next = curr;
                less = less.next;
            } else if (curr.data == x) {
                equal.next = curr;
                equal = equal.next;
            } else {
                greater.next = curr;
                greater = greater.next;
            }
            curr = curr.next;
        }

        // Connect the partitions together
        greater.next = null;

        // Connect equal to greater
        equal.next = greaterHead.next;

        // Connect less to equal
        less.next = equalHead.next;

        // New head of the rearranged list
        Node newHead = lessHead.next;

        return newHead;
    }

    static void PrintList(Node head) {
        Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
        Console.WriteLine();
    }

    static void Main(string[] args) {
        // Creating the linked list: 1 -> 4 -> 3 -> 2 -> 5 -> 2
        Node head = new Node(1);
        head.next = new Node(4);
        head.next.next = new Node(3);
        head.next.next.next = new Node(2);
        head.next.next.next.next = new Node(5);
        head.next.next.next.next.next = new Node(2);
		int x = 3;
        head = Partition(head, x);
        PrintList(head);
    }
}
JavaScript
// JavaScript program to partition a linked list
// around a given value.

class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}

function partition(head, x) {
    // Dummy head for nodes less than x
    let lessHead = new Node(0);

    // Dummy head for nodes equal to x
    let equalHead = new Node(0);

    // Dummy head for nodes greater than or equal to x
    let greaterHead = new Node(0);

    let less = lessHead;
    let equal = equalHead;
    let greater = greaterHead;

    let curr = head;

    while (curr !== null) {
        if (curr.data < x) {
            less.next = curr;
            less = less.next;
        } else if (curr.data === x) {
            equal.next = curr;
            equal = equal.next;
        } else {
            greater.next = curr;
            greater = greater.next;
        }
        curr = curr.next;
    }

    // Connect the partitions together
    greater.next = null;

    // Connect equal to greater
    equal.next = greaterHead.next;

    // Connect less to equal
    less.next = equalHead.next;

    // New head of the rearranged list
    let newHead = lessHead.next;

    return newHead;
}

function printList(head) {
    let curr = head;
    while (curr !== null) {
        console.log(curr.data);
        curr = curr.next;
    }
    console.log();
}

// Creating the linked list: 1 -> 4 -> 3 -> 2 -> 5 -> 2
let head = new Node(1);
head.next = new Node(4);
head.next.next = new Node(3);
head.next.next.next = new Node(2);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(2);
let x = 3;
head = partition(head, x);
printList(head);

Output
1 2 2 3 4 5 

Time complexity: O(n)
Auxiliary Space: O(1)

 



Next Article
Article Tags :
Practice Tags :

Similar Reads