递归解法 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);

    }
};
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务