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
.
1 遍历原链表,根据大小分别放入制作成另外两个链表。
2 遍历完成后,注意对两个链表的连接和结尾处理。
public ListNode partition(ListNode head, int x) {
if(head == null){
return null;
}
ListNode dummy1 = new ListNode(Integer.MIN_VALUE);
ListNode dummy2 = new ListNode(Integer.MAX_VALUE);
ListNode cur1 = dummy1;
ListNode cur2 = dummy2;
ListNode cur = head;
while(cur!=null){
if(cur.val>=x){
cur2.next = cur;
cur2 = cur2.next;
}
else{
cur1.next = cur;
cur1 = cur1.next;
}
cur = cur.next;
}
cur1.next = dummy2.next;
cur2.next = null;
return dummy1.next;
}