




Sponsored
Sponsored
This approach involves using two separate linked lists to store nodes that are less than x and nodes that are greater than or equal to x. You traverse the original list and attach each node to the appropriate list. Finally, you connect the two lists together to form the partitioned list.
Time Complexity: O(n), where n is the number of nodes in the list.
Space Complexity: O(1), as we only use a constant amount of extra space.
1#include <stdio.h>
2#include <stdlib.h>
3
4struct ListNode {
5    int val;
6    struct ListNode *next;
7};
8
9struct ListNode* partition(struct ListNode* head, int x) {
10    struct ListNode lessHead = {0, NULL}, greaterHead = {0, NULL};
11    struct ListNode *less = &lessHead, *greater = &greaterHead;
12
13    while (head) {
14        if (head->val < x) {
15            less->next = head;
16            less = less->next;
17        } else {
18            greater->next = head;
19            greater = greater->next;
20        }
21        head = head->next;
22    }
23    greater->next = NULL;
24    less->next = greaterHead.next;
25    return lessHead.next;
26}
27
28// Helper functions and testing code are omitted for brevity.This C implementation uses two dummy node pointers to build the 'less than x' and 'greater or equal to x' lists. It iterates through the original list only once, making the approach efficient.
This in-place rearrangement technique modifies the original list without the need of additional dummy nodes. This is accomplished by managing pointers to redefine segment connections efficiently.
Time Complexity: O(n)
Space Complexity: O(1)
1class ListNode 
        
This Java implementation utilizes the in-place rearrangement strategy with four pointers to keep track of the ends of two partitions, effectively handling connections to form the required result.