标签:accept container vector min 新建 types comment notice tac
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | /** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */classSolution {public:    ListNode* partition(ListNode* head, intx) {        /** we can use two vector<int> store different types of numbers, n1 record the number smaller than x, n2 record          *  the numbers no-smaller than x         */         if(head == NULL || head->next == NULL) returnhead;                  vector<int> n1, n2;         ListNode* p = head;         while(p != NULL){             p->val < x ? n1.push_back(p->val) : n2.push_back(p->val);             p = p->next;         }         p = head;         for(auto n: n1){             p->val = n;             p = p->next;         }         for(auto n: n2){             p->val = n;             p = p->next;         }                  returnhead;            }}; | 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | /** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */classSolution {public:    ListNode* partition(ListNode* head, intx) {        if(head == NULL || head->next == NULL) returnhead;                ListNode dummy1(0), dummy2(0);        ListNode* p1 = &dummy1, * p2 = &dummy2;        while(head != NULL){            // using reference to reduce the code lines            ListNode* & ref = head->val < x ? p1 : p2;            ref->next = head;            ref = ref->next;            /**            if(head->val < x){                p1->next = head;                p1 = p1->next;            }            else{                p2->next = head;                p2 = p2->next;            }            */            head = head->next;        }        p1->next = dummy2.next;                // notice that this step makes sure that there is no loop in the new list        p2->next = NULL;        returndummy1.next;    }}; | 
标签:accept container vector min 新建 types comment notice tac
原文地址:http://www.cnblogs.com/zhxshseu/p/2fce572ddcac587809a8981aa94095c5.html