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

Partition List

时间:2016-05-25 18:58:58      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:leetcode   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.

For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.


partition_list.h

#include <iostream>
#include <assert.h>
#include <stdlib.h>

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!"<<endl;
            return list;
        }

        node_p prev=node_x;
        node_p tmp=node_x->_next;
        while(tmp){
            if(tmp->_val<x){
                prev->_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<size;++i){
            node_p Node=new node (array[i]);
            prev->_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<<tmp->_val<<"  ";
        free(tmp);
        tmp=tmp->_next;
    }   
    cout<<endl;

    return 0;
}

运行结果:

技术分享


下面为leetcode实现的代码:

技术分享



《完》

本文出自 “零蛋蛋” 博客,请务必保留此出处http://lingdandan.blog.51cto.com/10697032/1783099

Partition List

标签:leetcode   partition list   

原文地址:http://lingdandan.blog.51cto.com/10697032/1783099

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