给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
解
遍历一次链表,然后使用2个数组分别保存下小于target和大于等于target的值,最后在遍历一次链表修改链表中的值。
public static ListNode partition(ListNode head, int x) {
ListNode res=head,temp = head;
int len = 0;
int s[] = new int[1000];
int b[] = new int[1000];
Arrays.fill(s, -147258369);
Arrays.fill(b, -147258369);
int idx_s = 0,idx_b =0;
while(temp!=null) {
if(temp.val<x) {
s[idx_s]=temp.val;
idx_s++;
}else {
b[idx_b]=temp.val;
idx_b++;
}
temp = temp.next;
}
idx_s = 0;idx_b =0;
while(s[idx_s]!=-147258369) {
head.val = s[idx_s];
idx_s++;
head=head.next;
}
while(b[idx_b]!=-147258369) {
head.val = b[idx_b];
idx_b++;
head=head.next;
}
return res;
}