[Leetcode] 86. Partition List 解题报告

本文介绍了一种链表分隔算法,该算法将链表中小于给定值x的节点放置在大于等于x的节点之前,并保持各分区内的相对顺序不变。通过创建两个虚拟头结点来分别收集小于x的节点和大于等于x的节点,最后合并两个列表。

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

题目

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

思路

这道题目在算法方面的难度也不大,主要是需要维护两个子列表a和b,其中子列表a保存值比x小的所有节点,子列表b保存值不小于x的所有节点。在遍历原始列表时,如果当前节点的值小于x,则将当前节点加入a;否则加入b。最后再将两个子列表合并起来。

对于链表头结点不确定的情况,我们常用的处理技巧就是增加虚拟头结点,方便处理不同情况。但在函数返回之前,一定要记得释放虚拟头结点所占用的内存空间。

代码

/**
 * 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 == NULL || head->next == NULL) {
            return head;
        }
        ListNode *small_head = new ListNode(0);     // small nodes
        ListNode *small_node = small_head;
        ListNode *no_small_head = new ListNode(0);  // greater or equal nodes
        ListNode *no_small_node = no_small_head;
        ListNode *node = head;
        while(node) {
            if(node->val < x) {
                small_node->next = node;
                small_node = small_node->next;
            }
            else{
                no_small_node->next = node;
                no_small_node = no_small_node->next;
            }
            node = node->next;
        }
        no_small_node->next = NULL;                 // connect two parts together
        small_node->next = no_small_head->next;
        head = small_head->next;
        delete small_head, no_small_head;
        return head;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值