栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

递归地反转Java中的链表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

递归地反转Java中的链表

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

  1. null(空列表)的反向是什么?空值。
  2. 一个元素列表的反向作用是什么?元素。

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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/385138.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号