Given a linked list and a value x, partition it such as 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
Idea: 1. check the empty only one node
2. Use smaller dummy pointer and large dummy pointer
3. compare the node value with x, if it is smaller, put it into the smaller list, otherwise, put it into the larger list.
4. assign the larger list except the dummy node into the last node of the smaller list
5. assign the last node point to null
/**
* 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) {
if(head==NULL || head->next == NULL) return head;
ListNode
*tempHead = new ListNode(x-1);
//tempHead->next = head;
ListNode
*secHead = new ListNode(x+1);
ListNode
*cur = head,
*cur1 = tempHead,
*cur2 = secHead;
while(cur!= NULL)
{
if(cur->val < x)
{
cur1->next = cur;
cur1 = cur1->next;
}
else
{
cur2->next = cur;
cur2= cur2->next;
}
cur = cur->next;
}
cur1->next = secHead->next;
cur2->next = NULL;
head = tempHead->next;
delete tempHead;
delete secHead;
return head;
}
};