86. Partition List**

86. Partition List**

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

Title Description

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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

C ++ implementation 1

Used smallerto link smaller than the xnode with the largerlinking of greater than / equal x. Note the last node:

q->next = nullptr;  // 防止指针指向混乱的问题
p->next = larger->next; // 小于 x 的节点在前面

Here is the complete code:

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if (!head) return nullptr;
        ListNode *smaller = new ListNode(0), *larger = new ListNode(0);
        auto p = smaller, q = larger;
        while (head) {
            if (head->val < x) {
                p->next = head;
                p = p->next;
            } else {
                q->next = head;
                q = q->next;
            }
            head = head->next;
        }
        q->next = nullptr;
        p->next = larger->next;
        return smaller->next;
    }
};
Published 455 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/Eric_1993/article/details/104978666