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.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
给定一个链表和一个值x,对它进行分区,使得小于x的所有节点都在大于或等于x的节点之前。您应该保留两个分区中的每一个节点的原始相对顺序。
思路:构造两个新的链表less,more,将小于x值的节点依次插入到less链表,将大于x值的节点依次到more链表。最后more链表的最后一个节点指向null,并且将more链表插入到less链表的后面。
代码如下:
public class PartitionList {
public static ListNode partition(ListNode head, int x) {
if(head == null || head.next == null ) {
return head;
}
ListNode less = new ListNode(0);
ListNode more = new ListNode(0);
ListNode node = head,pre = less,front = more;
while(node != null) {
if(node.val < x) {
pre.next= node;
pre = pre.next;
}else {
front.next = node;
front = front.next;
}
node = node.next;
}
front.next = null;
pre.next = more.next;
return less.next;
}
public static void main(String[] args) {
ListNode l10 = new ListNode(1);
ListNode l11 = new ListNode(2);
ListNode l12 = new ListNode(3);
ListNode l13 = new ListNode(2);
ListNode l14 = new ListNode(5);
ListNode l15 = new ListNode(2);
l10.next = l11;
l11.next = l12;
l12.next = l13;
l13.next = l14;
l14.next = l15;
l15.next = null;
ListNode node = partition(l10,3);
while(node != null) {
if(node.next == null) {
System.out.println(node.val);
}else{
System.out.print(node.val +"->");
}
node = node.next;
}
}
}
![](https://img-my.csdn.net/uploads/201710/27/1509066535_9780.png)