#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* partition(ListNode* head, int x) { if (head == NULL || head->next == NULL) return head; ListNode* cur = head; ListNode* last = head; while (cur){//寻找第一个小于x的节点 if (cur->val >= x){ last = cur;//记录最后一个大于等于x的节点 cur = cur->next; } else break; } if (cur == NULL) //所有节点的值都大于等于x return head; ListNode* first = head;//插入点的前一点 head = cur;//第一个小于x的节点就是头结点 if (head != first){//说明第一个小于x的节点前面有节点大于等于x last->next = head->next; head->next = first; } first = head;//插入点的前一点 cur = last->next; while (cur){ //我用的方法是一个节点一个节点的插入,而没有用小于x的[first,last)内的节点整体插入 if (cur->val < x){ if (first==last){//前面的节点的值都是小于x first = last = cur; cur = cur->next; }else{ //有节点的值大于等于x last->next = cur->next; cur->next = first->next; first->next = cur; first = cur; cur = last->next; } }else{ cur = cur->next; last = last->next; } } return head; } ListNode* createList(ListNode* head){ int numOfNode; int value; cout << "please input number of listNode:"; cin >> numOfNode; cin >> value; head = new ListNode(value); ListNode* cur = head; for (int i = 1; i < numOfNode; ++i){ cin >> value; ListNode* temp = new ListNode(value); cur->next = temp; cur = temp; } return head; } void printNode(ListNode* head){ ListNode* cur = head; while (cur){ cout << cur->val << " "; cur = cur->next; } cout << endl; } }; int main(){ ListNode* head = NULL; Solution lst; head = lst.createList(head); lst.printNode(head); head = lst.partition(head, 4); lst.printNode(head); system("pause"); return 0; }