[leetcode] Reorder List

本文介绍了一种使用递归方法优雅地解决链表重构问题的算法。该算法基于检查单链表是否为回文的问题骨架进行改进,通过递归调用实现链表元素的重新排列。

Problem:

此题的做法和 “检查单链表回文” 那道题的骨架是一样的,用 Recursive 的方法,简洁而优雅。

参考回文那道题:http://www.cnblogs.com/Antech/p/3847752.html

Code in Java:

public class Solution {
    
    void reorderList(ListNode head){
        reorderList(head, getListSize(head));
    }
    
    ListNode reorderList(ListNode head, int length){
        
        if(length == 0 || head == null){ // rare case
            return null;
        }else if(length == 1){
            ListNode temp = head.next;
            head.next = null;
            return temp;
        }else if(length == 2){
            ListNode temp = head.next.next;
            head.next.next = null;
            return temp;
        }else{
            ListNode forward = reorderList(head.next, length - 2);
            ListNode temp = forward.next;
            forward.next = head.next;
            head.next = forward;
            return temp;
        }
        
    }
}

转载于:https://www.cnblogs.com/Antech/p/3659914.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值