题目来源 86. 分隔链表 题目描述 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) { } }; 题目解析 class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode *curr = head; if(curr == nullptr || curr->next == nullptr){ return curr; } ListNode *small = new ListNode(); ListNode *large = new ListNode(); ListNode *s_move = small, *l_move = large; while (curr != nullptr){ if(curr->val < x){ s_move->next = curr; s_move = s_move->next; }else{ l_move->next = curr; l_move = l_move->next; } curr = curr->next; } l_move->next = nullptr; s_move->next = large->next; return small->next; } };