Leetcode学习笔记(86. 分隔链表)

在这里插入图片描述
方法一:遍历链表,用两个队列分别存储小于x和大于等于x的值,最后再合并:

/**
 * 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) {
        queue<ListNode*> LowData;
        queue<ListNode*> HightData;
        ListNode* cur = head;
        while(cur!=nullptr){
            if(cur->val<x)
                LowData.push(cur);
            else
                HightData.push(cur);
            cur = cur->next;
        }
        ListNode* out = new ListNode(0);
        cur = out;
        while(!LowData.empty()){
            cur->next = LowData.front();
            cur = cur->next;
            LowData.pop();
        }
        while(!HightData.empty()){
            cur->next = HightData.front();
            cur=cur->next;
            HightData.pop();
        }
        cur->next = nullptr;
        return out->next;
    }
};

方法二:引入了n个常量空间,因此想直接在链表上进行调整。需要引入双指针,先找到第一个不满足条件的值,再遍历后面寻找其他不满足条件的值插入。需要注意的是边界条件的情况以及删除插入过程的现成保护:

/**
 * 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==nullptr)
            return nullptr;;
        ListNode* new_head = new ListNode(0);
        new_head->next = head;
        ListNode* lp=new_head;
        ListNode* rp=head;
        while(rp->val<x){
            rp=rp->next;
            lp=lp->next;
            if(rp==nullptr)
                return head;
        }
        ListNode* mid = lp;
        while(rp!=nullptr){
            if(rp->val<x){
                ListNode* temp = rp;
                lp->next = rp->next;
                rp = rp->next;

                temp->next = mid->next;
                mid->next = temp;
                mid = temp;
            }
            else{
            rp=rp->next;
            lp=lp->next;
            }
        }
        return new_head->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值