Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
题目是给一个链表,一个数x,让排列链表,>=x的元素排在<x的元素后面,而且<x的部分和>=x的部分的元素顺序要和原链表中一致
思路:
方法一:交换节点
找到第一个>=x的元素,然后它后面的<x的元素都移到这个元素的前一个位置
注意不是移到固定的pre指针的后面,那样会变成倒序,
是保留原有的顺序,所以要不断更新pre节点。
public ListNode partition(ListNode head, int x) {
if(head == null || head.next == null) return head;
ListNode newHead = new ListNode();
newHead.next = head;
ListNode pre = newHead;
ListNode tmp = head;
ListNode preTmp = newHead;
//不能是tmp.next != null
//要把所有<x都跨过去,如果整个链表都<指定的x,直接可以让tmp到达最后的null,
//进而下一步也可跳过,如果停在最后的node,下一步就会产生交换,丢失掉最后的node
//可以用[1,1] 2测试
while(tmp != null) {
if(tmp.val >= x) break;
pre = pre.next;
tmp = tmp.next;
preTmp = preTmp.next;
}
while(tmp != null) {
if(tmp.val < x) {
preTmp.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
pre = pre.next;
tmp = preTmp.next;
} else {
preTmp = preTmp.next;
tmp = tmp.next;
}
}
return newHead.next;
}
方法二:保存节点值
用两个链表(比list快)分别保存 < x的值和 >= x 的值。
然后把这两个链表连接起来即可。
public ListNode partition(ListNode head, int x) {
if(head == null) return head;
ListNode small = new ListNode();
ListNode large = new ListNode();
ListNode sCur = small;
ListNode lCur = large;
while(head != null){
if(head.val<x){
sCur.next = head;
sCur = sCur.next;
}
else{
lCur.next = head;
lCur = lCur.next;
}
head=head.next;
}
sCur.next = large.next;
lCur.next=null;
return small.next;
}