给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
需要保证分割链表的稳定性。
public static ListNode partition(ListNode head, int x) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cursor = dummy;
ListNode lowerHead = null;
ListNode lowerTail = null;
while(cursor.next != null){
if(cursor.next.val < x){
if(lowerHead == null){
lowerHead = cursor.next;
lowerTail = cursor.next;
}else {
lowerTail.next = cursor.next;
lowerTail = lowerTail.next;
}
cursor.next = cursor.next.next;
}else {
cursor = cursor.next;
}
}
if(lowerTail != null) {
lowerTail.next = dummy.next;
}else {
lowerHead = dummy.next;
}
return lowerHead;
}
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}