zoukankan      html  css  js  c++  java
  • 单链表反转的递归实现(Reversing a Linked List in Java, recursively)

    转自Reversing a Linked List in Java, recursively


    There's code in one reply that spells it out, but you might find it easier to start from the bottom up, by asking and answering tiny questions (this is the approach in The Little Lisper):

    1. What is the reverse of null (the empty list)? null.
    2. What is the reverse of a one element list? the element.
    3. What is the reverse of an n element list? the reverse of the second element on followed by the first element.
    public ListNode Reverse(ListNode list)
    {
        if (list == null) return null; // first question
    
        if (list.next == null) return list; // second question
    
        // third question - in Lisp this is easy, but we don't have cons
        // so we grab the second element (which will be the last after we reverse it)
    
        ListNode secondElem = list.next;
    
        // bug fix - need to unlink list from the rest or you will get a cycle
        list.next = null;
    
        // then we reverse everything from the second element on
        ListNode reverseRest = Reverse(secondElem);
    
        // then we join the two lists
        secondElem.Next = list;
    
        return reverseRest;


  • 相关阅读:
    codefoces 1405 D Tree Tag
    洛谷P3413 萌数
    数位DP模板
    leetcode 统计所有可行路径
    Josephus Transform 加速置换
    牛客IOI周赛18-提高组 排列
    Find a way HDU
    Oil Deposits HDU
    Fire! UVA
    Pots POJ
  • 原文地址:https://www.cnblogs.com/noble/p/4144012.html
Copyright © 2011-2022 走看看