86. Partition List

来源:互联网 发布:算法分析 分治法总结 编辑:程序博客网 时间:2024/05/16 06:09

Given a linked list and a value x, partition it such that all nodes less thanx 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.

Subscribe to see which compa

/** * 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* pre=NULL;        ListNode* sec=NULL;        ListNode* root=NULL;        ListNode* p = NULL;        while(head)        {            ListNode* post =head->next;            if(head->val < x)            {                if(pre==NULL)                {                    pre=head;                    root=pre;                }                else                {                    pre->next=head;                     pre= pre->next;                }            }            else            {                if(sec==NULL)                {                    sec=head;                    p=sec;                }                else                {                    sec->next = head;                    sec=sec->next;                }            }            head=post;        }        if(sec)        {            sec->next=NULL;        }        if(pre)       {           pre->next=p;            return root;       }       return p;    }};

nies asked this question

0 0
原创粉丝点击