数据结构 - 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. 关docker hub上有些镜像的tag被标记““This image has vulnerabilities””2. debian - docker依赖的aufs-tools源码哪里可以找到啊?3. docker images显示的镜像过多,狗眼被亮瞎了,怎么办?4. angular.js - angular内容过长展开收起效果5. golang - 用IDE看docker源码时的小问题6. dockerfile - 为什么docker容器启动不了?7. 在windows下安装docker Toolbox 启动Docker Quickstart Terminal 失败!8. Docker for Mac 创建的dnsmasq容器连不上/不工作的问题9. docker网络端口映射,没有方便点的操作方法么?10. 前端 - angular报错?