码迷,mamicode.com
首页 > 其他好文 > 详细

86. Partition List

时间:2018-08-11 20:51:46      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:new   str   ++   current   tar   code   each   rip   esc   

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

86. Partition List

标签:new   str   ++   current   tar   code   each   rip   esc   

原文地址:https://www.cnblogs.com/hozhangel/p/9460805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!