给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解析:
就是将链表分为<x和>=x的两部分,然后再将两部分连接起来。需要四个指针,分别指向两个链表的头部和尾部。
代码:
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if(!head)
return head;
ListNode *cur=head;
ListNode *h=nullptr;
ListNode *tail=nullptr;
ListNode *highHead=nullptr;
ListNode *highTail=nullptr;
while(cur)
{
if(cur->val<x)
{
if(h==nullptr)//判断首部是否为空
{
h=cur;
}
else//向尾部添加
{
tail->next=cur;
}
tail=cur;
}
else
{
if(highHead==nullptr)
{
highHead=cur;
}
else
{
highTail->next=cur;
}
highTail=cur;
}
cur=cur->next;
}
if(h==nullptr)
return highHead;
tail->next=highHead;
if(highTail!=nullptr)
highTail->next=nullptr;
return h;
}
};
他山之石:
/**
* 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 || !head->next ) return head;
ListNode* dummy1 = new ListNode(-1);
ListNode* dummy2 = new ListNode(-1);
ListNode* pre1 = dummy1;
ListNode* pre2 = dummy2;
ListNode* cur = head;
while(cur){
if( cur->val < x){
pre1->next = cur;
pre1 = cur;
}
else {
pre2->next = cur;
pre2 = cur;
}
cur = cur->next;
}
pre2->next = NULL;
pre1->next = dummy2->next;
return dummy1->next;
}
};