zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    sudo
    Ansible模块
    Ansible自动化运维
    Sersync
    eclipse报错MA
    myeclipse报错MA
    通过StringBuilder的reverse()实现倒序
    位运算实现高效互换
    scanf("%s",s)与gets(s)
    异或运算符实现简单加密
  • 原文地址:https://www.cnblogs.com/hozhangel/p/9460805.html
Copyright © 2011-2022 走看看