题目:
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal tox.
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
.
思路:
准备两个指针,一个保存小于target的节点,一个保存大于等于target的节点。循环一次完成整个算法。
代码:
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode * lt=NULL;
ListNode * p1=NULL;
ListNode * gt=NULL;
ListNode * p2=NULL;
ListNode * p=head;
while(p != NULL)
{
if(p->val < x)
{
if(lt == NULL)
{
lt = p;
p1 = lt;
}
else
{
p1->next = p;
p1 = p1->next;
}
p = p->next;
p1->next = NULL;
}
else
{
if(gt == NULL)
{
gt = p;
p2 = gt;
}
else
{
p2->next = p;
p2 = p2->next;
}
p = p->next;
p2->next = NULL;
}
};
if(p1 == NULL)
{
return gt;
}
else
{
p1->next = gt;
return lt;
}
}
};