PartitionList

描述

成都创新互联专注于惠济网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供惠济营销型网站建设,惠济网站制作、惠济网页设计、惠济网站官网定制、小程序开发服务,打造惠济网络公司原创品牌,更为您提供惠济网站排名全网营销落地服务。

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.

partition_list.h

#include 
#include 
#include 

using namespace std;

typedef struct ListNode {
    int _val;
    ListNode *_next;
    ListNode(int x) : _val(x), _next(NULL)
    {}  
}node,*node_p;

class Solution
{
public:
    node_p partition(node_p &list,int x)
    {   
        //参数检查
        if(list==NULL)
            return NULL;
     
        node dummy(-1);
        node_p head=&dummy;
        head->_next=list;
        
        node_p first=head;
        
        //找_val为x的结点
        node_p node_x=list;
        while(node_x!=NULL && node_x->_val!=x){
            node_x=node_x->_next;
            first=first->_next;
        }
        if(node_x==NULL){
            cout<<"not find node_x!"<_next;
        while(tmp){
            if(tmp->_val_next=tmp->_next;
                tmp->_next=node_x;
                first->_next=tmp;
                first=first->_next;
                tmp=node_x->_next;
            }else{
                tmp=tmp->_next;
                prev=prev->_next;
            }
        }
        return head->_next;
    }

    //构造一个链表
    node_p create_list(int *array,int size)
    {
        assert(array);

        node dummy(-1);
        node_p prev=&dummy;
        node_p head=prev;
        for(int i=0;i_next=Node;
            prev=prev->_next;
        }
        return head->_next;
    }
};

partition_list.cpp

#include "partition_list.h"

using namespace std;

int main()
{
    int array[]={1,4,3,2,5,2};
    Solution s1; 
    node_p list=s1.create_list(array,sizeof(array)/sizeof(array[0]));
    node_p newlist=s1.partition(list,4);
    
    node_p tmp=newlist;
    while(tmp){
        cout<_val<<"  ";
        free(tmp);
        tmp=tmp->_next;
    }   
    cout<

运行结果:

Partition List

下面为leetcode实现的代码:

Partition List

《完》


文章标题:PartitionList
文章网址:http://pwwzsj.com/article/jdhjhi.html