[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;
        }
        
    }
}
posted @ 2014-04-12 03:08  门对夕阳  阅读(356)  评论(0编辑  收藏  举报