【技巧】LeetCode 86. Partition List

本文提供两种解决LeetCode 86题(分区列表)的方法。第一种方法使用额外空间创建两个新链表,再进行拼接;第二种方法通过调整链表指针实现,空间复杂度优化到O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 86. Partition List

Solution1:
我的答案,时间复杂度 O(n) O ( n ) ,空间复杂度 O(n) O ( 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) {
        struct ListNode* smallHead = new ListNode(-1), *bigHead = new ListNode(-1), *cur = head;
        struct ListNode* smalltemp = smallHead, *bigtemp = bigHead;
        while (cur) {
            if (cur->val < x) {
                smalltemp->next = new ListNode(cur->val);
                smalltemp = smalltemp->next;
            }
            else {
                bigtemp->next = new ListNode(cur->val);
                bigtemp = bigtemp->next;
            }
            cur = cur->next;
        }
        smalltemp->next = bigHead->next;
        return smallHead->next;
    }
};

Solution2:
参考网址:http://www.cnblogs.com/grandyang/p/4321292.html
值得借鉴的技巧!!!
加了一个头结点,巧妙地避免了复制结点的操作,时间复杂度没变,但空间复杂度降为 O(1) O ( 1 )

class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        if (!head) return head;
        ListNode *dummy = new ListNode(-1);
        ListNode *newDummy = new ListNode(-1);
        dummy->next = head;
        ListNode *cur = dummy, *p = newDummy;
        while (cur->next) {
            if (cur->next->val < x) {
                p->next = cur->next;
                p = p->next;
                cur->next = cur->next->next;
                p->next = NULL;
            } else {
                cur = cur->next;
            }
        }
        p->next = dummy->next;
        return newDummy->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值