leetcode 86. Partition List

来源:互联网 发布:电视盒子软件2017 编辑:程序博客网 时间:2024/05/17 09:25

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.

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

way-1: use 2 vector save value

way-2: 操作链表

/** * 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)     {        //way-1        /*        vector<int> xiao;        vector<int> da;        ListNode *p=head;        while(p)        {            if(p->val<x)                xiao.push_back(p->val);            else                da.push_back(p->val);            p=p->next;         }        p=head;        for(int i=0;i<xiao.size();i++)        {            p->val=xiao[i];            p=p->next;        }        for(int i=0;i<da.size();i++)        {            p->val=da[i];            p=p->next;        }        return head;         */                //way-2        if (!head)               return head;        ListNode hhead(-1);        hhead.next = head;        ListNode * small = &hhead;        ListNode * now = head;        ListNode * last = small;        while (now)        {            if (now->val >= x)            {                now = now->next;                last = last->next;            }            else            {                if (now == small->next)                {                    now = now->next;                    last = last->next;                }                else                {                    last->next = now->next;                    now->next = small->next;                    small->next = now;                    now = last->next;                }                small = small->next;            }        }        return hhead.next;    }};


原创粉丝点击