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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null || head.next==null) return head;
ListNode minHead = new ListNode(-1);
ListNode minP = minHead;
ListNode maxHead = new ListNode(-1);
ListNode maxP = maxHead;
while(head!=null){
if(head.val<x){
minP.next = head;
minP = minP.next;
}else{
maxP.next = head;
maxP = maxP.next;
}
head = head.next;
}
maxP.next = null; //以防超出内存限制
minP.next = maxHead.next;
return minHead.next;
}
}