Partition List

来源:互联网 发布:电信网络诈骗数额 编辑:程序博客网 时间:2024/06/06 16:18
/** * 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* preserve=NULL;        ListNode* scan=NULL;        ListNode* cphead=head;        while(cphead)        {            int val=cphead->val;            if(val<x)            {               preserve=cphead;               scan=cphead;            }            else            {                scan=cphead;                break;               }            cphead=cphead->next;        }        if(!cphead)        {            return head;        }        else        {            while(scan->next)            {                int val=scan->next->val;                if(val<x)                {                    ListNode* tmp=scan->next->next;                    if(preserve)                    {                        scan->next->next=preserve->next;                        preserve->next=scan->next;                        preserve=preserve->next;                    }                    else                    {                        scan->next->next=head;                        preserve=scan->next;                        head=preserve;                                            }                    scan->next=tmp;                 }                else                {                    scan=scan->next;                   }            }            return head;        }            }};

0 0
原创粉丝点击