数据结构 - java翻转链表是如何实现的?
问题描述
public class Node { public int value; public Node next; public Node(int data) {this.value = data; } public Node reverse(Node head) {Node pre = null;Node next = null;while (head != null) { next = head.next; head.next = pre; pre = head; head = next;}return pre; }
这段代码while循环中他是如何翻转的?想要详细一点的,debug了几次还是没弄懂具体是怎么回事
问题解答
回答1:参考一下,理解目的就比较好理解了。容易混乱的地方就是从右往左来处理,因为得先把后面的东西存起来,不然被覆盖掉就丢了。
prehead +----+ +----+ +> +----+| | | | | | || | | | | | || | | | | | |+----+ +----+ | +----+| | | | | | || | | | | | |+----+ +-+--+ | +----+ | | +-----+ prehead nextnext = head.next;+----+ +----+ +> +----+| | | | | | || | | | | | || | | | | | |+----+ +----+ | +----+| | | | | | || | | | | | |+----+ +-+--+ | +----+ | | +-----+ prehead next+----+ <+ +----+ +----+| | | | | | || | | | | | || | | | | | |+----+ | +----+ +----+| | | | | | || | | | | | |+----+ | +-+--+ +----+| | head.next = pre;+----+ next preheadpre = head;+----+ <+ +----+ +----+ head = next;| | | | | | || | | | | | || | | | | | |+----+ | +----+ +----+| | | | | | || | | | | | |+----+ | +-+--+ +----+| |+----+回答2:
Ps:建议先多了解一下链表
相关文章:
1. angular.js - 不适用其他构建工具,怎么搭建angular1项目2. docker镜像push报错3. linux运维 - python远程控制windows如何实现4. javascript - 如何获取未来元素的父元素在页面中所有相同元素中是第几个?5. javascript - 分类编辑保留之前分类名称6. 关于Java引用传递的一个困惑?7. 如何分别在Windows下用Winform项模板+C#,在MacOSX下用Cocos Application项目模板+Objective-C实现一个制作游戏的空的黑窗口?8. javascript - canvas 裁剪空白区域9. javascript - 后端传过来的数据格式是这样,如何使用?10. javascript - js判断一个数组是否重复
