【LeetCode-86】分隔链表

问题

给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

你应当 保留 两个分区中每个节点的初始相对位置。

示例

解答

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* dum_more = new ListNode(0);
        ListNode* dum_less = new ListNode(0);
        ListNode *w_more = dum_more, *w_less = dum_less;
        while (head) {
            if (head->val < x) w_less = w_less->next = head;
            else w_more = w_more->next = head;
            head = head->next;
        }
        w_less->next = dum_more->next;
        w_more->next = nullptr; // w_more可能不是最末尾一个节点,需要断链
        return dum_less->next;
    }
};

重点思路

类似于奇偶链表的做法。本题是链表快速排序的基础,需要掌握。

posted @ 2021-03-27 13:17  tmpUser  阅读(50)  评论(0编辑  收藏  举报