数据结构 - 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下的nginx压力测试2. angular.js - angular内容过长展开收起效果3. java - EventBus 3.0 nullPoint异常?4. docker镜像push报错5. 为什么我ping不通我的docker容器呢???6. docker - 如何修改运行中容器的配置7. Docker for Mac 创建的dnsmasq容器连不上/不工作的问题8. javascript - fis3使用MD5但是如何引用?9. javascript - Img.complete和img.onload判断图片加载完成有什么区别?10. angular.js使用$resource服务把数据存入mongodb的问题。
