数据结构 - 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 start -a dockername 老是卡住,什么情况?2. docker images显示的镜像过多,狗眼被亮瞎了,怎么办?3. 小白学python的问题 关于%d和%s的区别4. 在mac下出现了两个docker环境5. docker - 如何修改运行中容器的配置6. vim - docker中新的ubuntu12.04镜像,运行vi提示,找不到命名.7. mac连接阿里云docker集群,已经卡了2天了,求问?8. docker镜像push报错9. angular.js - 怎样实现点击 “分数” 后按分数升序和降序排列?10. 关于docker下的nginx压力测试

网公网安备