Leetcode—86.分隔链表【中等】

2023每日刷题(六十九)

Leetcode—86.分隔链表

Leetcode—86.分隔链表【中等】_第1张图片

实现代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* partition(struct ListNode* head, int x) {
    struct ListNode* small = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* big = (struct ListNode*)malloc(sizeof(struct ListNode));
    small->next = NULL;
    big->next = NULL;
    struct ListNode* r1 = small;
    struct ListNode* r2 = big;
    while(head != NULL) {
        if(head->val < x) {
            r1->next = head;
            r1 = head;
        } else {
            r2->next = head;
            r2 = head;
        }
        head = head->next;
    }
    r2->next = NULL;
    r1->next = big->next;
    return small->next;
}

运行结果

Leetcode—86.分隔链表【中等】_第2张图片
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,链表,linux,经验分享,c语言,算法)