86. Partition List

86. Partition List

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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5


/**
 * 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* new_node = new ListNode(0);
        new_node->next = head;

        ListNode* pre = new_node;
        ListNode* curr = head;
        ListNode* move = head;

        while (curr != NULL && curr->val < x)    //for the preserve of the original relative order of the nodes
        {
            move = curr;
            pre = curr;
            curr = curr->next;
        }

        while (curr != NULL)
        {
            if (curr->val >= x) //if the value bigger than x, curr just index the next node 
            {
                move = curr;
                curr = curr->next;
            }
            else if(curr->val < x) //if the value smaller than x , move it to the head 
                                   //(preserve of the original relative order of the nodes when move the node ahead)
            {                      //pre is the last node of which is smaller than x,
                                   //move's duty is traverse
                                   //cur is the current node 
                move->next = curr->next;
                curr->next = pre->next;
                pre->next = curr;

                pre = curr;
                curr = move->next;
            }
        }
        ListNode* temp = new_node;
        delete new_node;
        return temp->next;
    }
};

referenceL:C++ one pass solution

posted @ 2018-08-11 19:33  hozhangel  阅读(136)  评论(0编辑  收藏  举报