Reorder List

来源:互联网 发布:两组数据差值的标准差 编辑:程序博客网 时间:2024/06/08 07:50
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {private:    ListNode* reverse(ListNode* head,int len)    {        if(len==1)        {            return head;        }        else if(len==2)        {            ListNode* tmp=head;            head=head->next;            head->next=tmp;            tmp->next=0;            return head;        }        else        {            ListNode *pre=head;            ListNode *cur=pre->next;            ListNode *next=cur->next;            pre->next=0;            while(next)            {                cur->next=pre;                pre=cur;                cur=next;                next=next->next;            }            cur->next=pre;            return cur;        }    }public:    void reorderList(ListNode *head) {        int len=0;        ListNode *cphead=head;        while(cphead)        {            len++;            cphead=cphead->next;        }        if(len<3)        {            return;        }        int secondpart=len/2;        cphead=head;        for(int i=0;i<secondpart;++i)        {            cphead=cphead->next;        }        ListNode *second=cphead->next;        cphead->next=0;        ListNode* secondhead=reverse(second,len-len/2-1);        while(secondhead)        {            ListNode* tmp=head;            ListNode* tmp2=secondhead;            head=head->next;            tmp->next=secondhead;            secondhead=secondhead->next;            tmp2->next=head;        }    }};

0 0
原创粉丝点击