LeetCode Partition List

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    ListNode *partition(ListNode *head, int x) {

        ListNode* small = NULL;

        ListNode* great = NULL;

        ListNode* scur = NULL;

        ListNode* gcur = NULL;

        

        ListNode* cur = head;

        while (cur != NULL) {

            if (cur->val < x) {

                add_node(scur, cur);

                if (small == NULL) small = cur;

            } else {

                add_node(gcur, cur);

                if (great == NULL) great = cur;

            }

            cur = cur->next;

        }

        if (small != NULL) {

            scur->next = great;

            head = small;

        } else {

            head = great;

        }

        if (great != NULL) gcur->next = NULL;

        return head;

    }

    

    void add_node(ListNode* &last, ListNode* n) {

        if (last == NULL) {

            last = n;

        } else {

            last->next = n;

            last = n;

        }

    }

};

 水一发

你可能感兴趣的:(partition)