数据结构 - 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. 修改mysql配置文件的默认字符集重启后依然不生效2. 请教一个python字符串处理的问题?3. javascript - 正则匹配字符串特定语句后的数字4. java - mybatis源码分析5. css - html根字体设置成很大的值后, 包裹了行内元素的div莫名变高是什么原因6. 老师,你这两条斜杠的是怎么注释的?7. python - scrapy 处理 文章 分页的内容8. javascript - main head .intro-text{width:40%} main head{display:flex}为何无效?9. java - servlet的init方法和选择Filter的init方法来加载配置文件,二者有何区别?10. javascript - 一个前端的自我修养

网公网安备