您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

递归地反转Java中的链表

递归地反转Java中的链表

一个答复中有代码将其说明清楚,但是你可能会发现,通过问和回答一些微小的问题(这是The Little Lisper中的方法),更容易从头开始。

n元素列表的反向操作是什么?列表其余部分的倒序,后跟第一个元素。

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;
}
java 2022/1/1 18:19:07 有518人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶