最简单的就是用O(n)的额外空间
不过也没必要,就用两个指针就好啦。。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *partition(ListNode *head, int x) { if(head == nullptr) return head; ListNode* left = new ListNode(-1); ListNode* right = new ListNode(-1); ListNode* lcur = left; ListNode* rcur = right; ListNode* curr = head; while(curr) { if(curr -> val < x) { lcur -> next = curr; lcur = curr; } else { rcur -> next = curr; rcur = curr; } curr = curr -> next; } lcur -> next = right -> next; rcur -> next = nullptr; return left -> next; } };