Partition List

来源:互联网 发布:瘦骨精油副作用知乎 编辑:程序博客网 时间:2024/06/08 00:54
/** * 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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        ListNode *res = new ListNode(0);        res->next=head;        ListNode *temp=head, *pre=res;        ListNode *big=NULL, *prebig=NULL, *small=NULL, *presmall=NULL;        while (temp) {            if (temp->val>=x && big==NULL) {                prebig=pre;                big=temp;            }            if (temp->val<x && big!=NULL) {                presmall=pre;                small=temp;                temp=big;                if (big->next!=small) {                    presmall->next=small->next;                    small->next=big;                    prebig->next=small;                    prebig=small;                                    }else {                    pre=small;                    big->next=small->next;                    small->next=big;                    prebig->next=small;                    prebig=small;                }            }                        pre=temp;            temp=temp->next;        }        return res->next;    }};