| 15 | class Solution { |
| 16 | public: |
| 17 | ListNode* partition(ListNode* head, int x) { |
| 18 | if (head == NULL) return head; |
| 19 | ListNode * header = new ListNode(0); |
| 20 | header->next = head; |
| 21 | auto p1 = header, p2 = header; // p1, p2 not NULL |
| 22 | // p1 -> the last number < x, p2 -> cur |
| 23 | while (p2 != NULL and p2->next != NULL) { // see the next node value |
| 24 | if (p2->next->val < x) { |
| 25 | if ( p1 == p2 ) { |
| 26 | p1 = p1->next; |
| 27 | p2 = p2->next; |
| 28 | continue; |
| 29 | } |
| 30 | // swap |
| 31 | auto p3 = p2->next, p4 = p3->next; |
| 32 | auto p1n = p1->next; |
| 33 | p1->next = p3; |
| 34 | p3->next = p1n; |
| 35 | p2->next = p4; |
| 36 | p1 = p1->next; |
| 37 | } else |
| 38 | p2 = p2->next; |
| 39 | } |
| 40 | return header->next; |
| 41 | } |
| 42 | }; |
| 43 | |
| 44 | int main() { |