/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param x int整型 
     * @return ListNode类
     */
    ListNode* partition(ListNode* head, int x) {
      if (head == nullptr) {
        return head;
      }
      
      auto node = std::make_unique<ListNode>(-1);
      node->next = head;
      
      ListNode *end = node.get();
      
      //  尾结点
      while (end->next) {
        end = end->next;
      }
      
      ListNode *left = node.get(), *right = end;
      
      while (left->next != end) {
        if (left->next->val >= x) {
          right->next = left->next;
          right = right->next;
          left->next = left->next->next;
          right->next = nullptr;
        } else {
          left = left->next;
        }
      } 
      
      if (end->val >= x) {
        right->next = end;
        left->next = end->next;
        end->next = nullptr;
      }
      
      return node->next;
    }
};