给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x){
struct ListNode* left_head=NULL;
struct ListNode* left_tmp=NULL;
struct ListNode* right_head=NULL;
struct ListNode* right_tmp=NULL;
while(head)
{
if(head->val<x)
{
if(!left_head)
{
left_head=head;
left_tmp=head;
}
else
{
left_tmp->next=head;
left_tmp=left_tmp->next;
}
}
else
{
if(!right_head)
{
right_head=head;
right_tmp=head;
}
else
{
right_tmp->next=head;
right_tmp=right_tmp->next;
}
}
head=head->next;
}
if(left_head)left_tmp->next=right_head;
if(right_head)right_tmp->next=NULL;
return left_head==NULL?right_head:left_head;
}
执行用时 : 8 ms, 在Partition List的C提交中击败了92.70% 的用户
内存消耗 : 7.3 MB, 在Partition List的C提交中击败了6.94% 的用户