递归解法 c++

重排链表

http://www.nowcoder.com/questionTerminal/3d281dc0b3704347846a110bf561ef6b

看了下题解里的方法 都是双指针 或者翻转重建链表之类的,我是用递归做的,可能效率不是很好? 但在我看来还挺直观的。
其实就是头结点指向尾结点 不断的迭代这个做法就可以,要注意标记尾结点的前一个结点pre,在头连尾之后 ,要把前一个结点pre指向空, 然后递归head->next。

class Solution {
public:
    ListNode* reorder(ListNode* head){
        if(head==nullptr)
            return nullptr;
        ListNode* post=head;
        ListNode* pre=nullptr;
        int len=1;
        while(post->next!=nullptr){
            pre=post;
            post=post->next;
            len++;
        }
        if(len<3) return head;
        ListNode* root=head;
        ListNode* next=root->next;
        root->next=post;
        pre->next=nullptr;
        post->next=reorder(next);

        return root;
    }
    void reorderList(ListNode *head) {
        if(head==nullptr)
            return;
        head=reorder(head);

    }
};
全部评论

相关推荐

缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务