数据结构 - 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. vue.js - vuejs 折叠面板的展开收缩动画应该怎么实现?用vue自带的过渡效果还是css3?2. css3 - css里面自定义字体3. javascript - 百度echarts series数据更新问题4. css - chrome (mac)中文字体乱码,修改font-family会有改变5. 错误:java.lang.NoSuchMethodError:org.objectweb.asm.ClassWriter(I)V6. java动态规划算法——硬币找零问题实例分析7. 通过html5页面如何打开QQ和地图8. css3 - CSS标点换行9. 在windows下安装docker Toolbox 启动Docker Quickstart Terminal 失败!10. docker网络端口映射,没有方便点的操作方法么?
