LeetCode 86 Partition List

将链表按给定元素分成大于和小于的部分

标签:链表类题目LeetCode发布于:编辑于:浏览量:1453

概述

https://leetcode.com/problems/partition-list/

解法

读错题了就离谱,好好审题呀。

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        auto head1 = new ListNode;
        auto head2 = new ListNode;
        auto a = head1;
        auto b = head2;
        auto d = head;
        while (d) {
            if (d->val < x) {
                a->next = d;
                a = a->next;
            } else {
                b->next = d;
                b = b->next;                
            }
            d = d->next;
        }
        a->next = head2->next;
        b->next = nullptr;
        return head1->next;
    }
};