86. 分隔链表
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 //直接模拟,建立两个虚拟节点就可以了 10 class Solution 11 { 12 public: 13 ListNode* partition(ListNode* head, int x) 14 { 15 ListNode* dummy1 = new ListNode(-1); 16 ListNode* dummy2 = new ListNode(-1); 17 18 ListNode* pre1 = dummy1; 19 ListNode* pre2 = dummy2; 20 21 while(head) 22 { 23 if(head->val < x) 24 { 25 pre1->next = head; 26 head = head->next; 27 pre1 = pre1->next; 28 } 29 else 30 { 31 pre2->next = head; 32 head = head->next; 33 pre2 = pre2->next; 34 } 35 } 36 pre1->next = dummy2->next; 37 pre2->next = NULL; 38 39 return dummy1->next; 40 } 41 };
Mamba never out

浙公网安备 33010602011771号