题目描述:
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
算法1:
指针small 维护比 x 值小的链表,nextsmall 查找下一个小的节点,然后插入到 samll->next位置。
/**
* 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 *p = new ListNode(0); // 新建一个头结点,方便操作
p->next = head;
head = p;
ListNode *small =head;
while(small->next!=NULL && small->next->val < x)
small=small->next;
ListNode *nextsmall = small->next;
ListNode *fro = small; // *fro 指向nextsmall的前一个节点,方便移动nextmall节点
while(nextsmall!=NULL)
{
if(nextsmall->val < x)
{
p = nextsmall;
fro->next = fro->next->next;
p->next = small->next;
small->next = p;
nextsmall = fro->next;
small = small->next;
}
else
{
fro = nextsmall;
nextsmall = nextsmall -> next;
}
}
return head->next;
}
};
算法2:(此法比较简单)
直接新建两个链表,分别将比x 大的节点,小的节点放在两个链表中,然后将两个节点拼接即可。