CM11 链表分割

链表分割_牛客题霸_牛客网 (nowcoder.com)

一、思路分析

二、源码


CM11 链表分割_第1张图片

一、思路分析

创建两个链表small、big

遍历原来链表

比X小的节点尾插到small

比X大的节点尾插到big

最后来链接起来

这样不会改变各个节点的相对顺序

二、源码

ListNode* partition(ListNode* pHead, int x) {
    // write code here
    struct ListNode* smallhead = NULL, * bighead = NULL;
    struct ListNode* samlltail = NULL, * bigtail = NULL;
    struct ListNode* cur = pHead;
    while (cur) {
        if (cur->val > x)
        {
            if (bighead == NULL)
            {
                bighead = bigtail = cur;
            }
            else
            {
                bigtail->next = cur;
                bigtail = bigtail->next;
            }
        }
        else
        {
            if (smallhead == NULL)
            {
                smallhead = samlltail = cur;
            }
            else
            {
                samlltail->next = cur;
                samlltail = samlltail->next;
            }
        }
        cur = cur->next;
    }
    bigtail->next = NULL;
    samlltail->next = bighead;
    return smallhead;
}

你可能感兴趣的:(力扣题目集,链表,数据结构)