leetcode: 86. 分隔链表

https://leetcode-cn.com/problems/partition-list/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* partition(struct ListNode* head, int x){
    if (NULL == head) return head;

    struct ListNode result;
    struct ListNode *node = &result;
    node->next = head;

    struct ListNode *pre = NULL;
    struct ListNode *insert_pre = node;
    struct ListNode *inser_node = NULL; // 找到的第一个大于等于val的值
    struct ListNode *next = NULL;

    bool find = false;
    
    while (head) {
        if (find == false) {
            if (head->val < x) {
                //当前遍历的节点val都小于x, 直接转到下一个即可
                insert_pre = head;
                head = head->next;
            } else {
                // 当前遍历的节点的值大于等于x, 那么后续遍历到的小于x的节点都需要挪到这个节点之前
                inser_node = head;
                pre = head;
                head = head->next;
                find = true;
            }
        } else {
            if (head->val >= x) {
                pre = head;
                head = head->next;
            } else {
                // 需要把当前的节点挪到第一个大于x的节点之前
                next = head->next; //记录当前节点的下一个节点
                
                //插入到第一个大于x的节点之前 inser_node 之前
                insert_pre->next = head;
                head->next = inser_node;

                insert_pre = insert_pre->next;
                pre->next = next;
                head = next;
            }
        }
    }

    return result.next;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值