题目
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
思路
建立两个链表,一个连接比x小的节点,一个连接比x大的节点,最后将这两个链表连接起来
代码
public ListNode partition(ListNode head, int x) {
ListNode minhead = new ListNode(0);
ListNode min = minhead;
ListNode maxhead = new ListNode(0);
ListNode max = maxhead;
while(head!=null){
if(head.val<x){
min.next = head;
min = min.next;
}else{
max.next = head;
max = max.next;
}
head = head.next;
}
//记得将结尾连接null
max.next = null;
min.next = maxhead.next;
return minhead.next;
}