Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions.
Example:
Input: head = 3->5->8->5->10->2->1, x = 5
Output: 3->1->2->10->5->5->8
Solutions
Solution 1: Concatenating Lists
We create two lists, left and right, to store nodes that are less than x and nodes that are greater than or equal to x, respectively.
Then we use two pointers p1 and p2 to point to the last node of left and right respectively, initially both p1 and p2 point to a dummy head node.
Next, we traverse the list head. If the value of the current node is less than x, we add the current node to the end of the left list, i.e., p1.next = head, and then set p1 = p1.next; otherwise, we add the current node to the end of the right list, i.e., p2.next = head, and then set p2 = p2.next.
After the traversal, we point the tail node of the left list to the first valid node of the right list, i.e., p1.next = right.next, and then point the tail node of the right list to a null node, i.e., p2.next = null.
Finally, we return the first valid node of the left list.
The time complexity is $O(n)$, where $n$ is the length of the list. The space complexity is $O(1)$.
1 2 3 4 5 6 7 8 910111213141516171819202122
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution:defpartition(self,head:ListNode,x:int)->ListNode:left,right=ListNode(0),ListNode(0)p1,p2=left,rightwhilehead:ifhead.val<x:p1.next=headp1=p1.nextelse:p2.next=headp2=p2.nexthead=head.nextp1.next=right.nextp2.next=Nonereturnleft.next
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcpartition(head*ListNode,xint)*ListNode{left,right:=&ListNode{},&ListNode{}p1,p2:=left,rightfor;head!=nil;head=head.Next{ifhead.Val<x{p1.Next=headp1=p1.Next}else{p2.Next=headp2=p2.Next}}p1.Next=right.Nextp2.Next=nilreturnleft.Next}