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的数分别放到两个链表中,然后小的链表后面接上大的链表即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode *left = new ListNode(-1);
ListNode *right = new ListNode(-1);
ListNode *ptr = head, *ptr_l = left, *ptr_r = right;
while(ptr)
{
if(ptr->val < x)
{
ptr_l->next = ptr;
ptr = ptr->next;
ptr_l = ptr_l->next;
ptr_l->next = NULL;
}
else
{
ptr_r->next = ptr;
ptr = ptr->next;
ptr_r = ptr_r->next;
ptr_r->next = NULL;
}
}
ptr_l->next = right->next;
return left->next;
}
};