思想:借助辅助空间,同时维护两个链表:lowList按原先顺序保存所有val小于x的节点,hightList按原先顺序保存所有val>=x的节点,最后将这两个链表拼接起来即可
时间复杂度O(N),空间复杂度O(1)
class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null)return head;
ListNode lowList = new ListNode(-1);
ListNode lowRear = lowList;
ListNode highList = new ListNode(-1);
ListNode highRear = highList;
while(head!=null){
ListNode next = head.next;
if(head.val<x){
head.next = null;//这里不能忘,否则有可能出现环
lowRear.next = head;
lowRear = lowRear.next;
}else{
head.next = null;
highRear.next = head;
highRear = highRear.next;
}
head = next;
}
lowRear.next = highList.next;//拼接
return lowList.next;
}
}