题目链接:https://leetcode-cn.com/problems/partition-list/
题目大意
略。
分析
空间复杂度 O(1) 的做法蛮有意思的,另外加头结点可以少写很多代码。
代码如下
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* partition(ListNode* head, int x) { 12 ListNode *leftH, *leftT, *rightH, *rightT, *p = head; 13 leftH = leftT = new ListNode(0); 14 rightH = rightT = new ListNode(0); 15 16 while(p != NULL) { 17 if(p->val < x) { 18 leftT->next = p; 19 leftT =leftT->next; 20 21 } 22 else if(p->val >= x) { 23 rightT->next = p; 24 rightT = rightT->next; 25 } 26 p = p->next; 27 } 28 29 leftT->next = rightH->next; 30 rightT->next = NULL; 31 32 return leftH->next; 33 } 34 };