力扣86. 分隔链表

2023-12-22 08:44:56

分割

  • 思路:
    • 创建两个链表,small 存放小于 x 的元素,large 放大于或等于 x 的元素;
    • 遍历完原链表之后,将 small 链表与 large 链表链接;
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* small = new ListNode(0);
        ListNode* sHead = small;
        ListNode* large = new ListNode(0);
        ListNode* lHead = large;

        while (head != nullptr) {
            if (head->val < x) {
                small->next = head;
                small = small->next;
            } else {
                large->next = head;
                large = large->next;
            }

            head = head->next;
        }

        // link s -> l
        large->next = nullptr;
        small->next = lHead->next;

        return sHead->next;
    }
};

文章来源:https://blog.csdn.net/N_BenBird/article/details/135142933
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。