逆转单向链表

逆转前: 1 -> 2 -> 3 -> 4 -> 5 -> null

逆转后: 5 -> 4 -> 3 -> 2 -> 1 -> null

个人博客地址:逆转单向链表

方法一、循环迭代

public Node reverse(Node head) {
if (head == null || head.next == null) {
return head;
}
// 取前面节点
Node pre = head;
// 取后面节点
Node cur = head.next;
// 临时节点
Node temp = null;
while (cur != null) {
// 1. 保存后节点的指向节点 因为要替换后节点的指向节点为他的前节点
temp = cur.next;
// 2. 把后节点的指向的节点替换成前节点
cur.next = pre;
// 下一轮要替换的前节点和后节点
// 第一次 pre = 1 cur =2 || 那第二次 就得 pre = 2 cur = 3
pre = cur;
cur = temp;
}
// 在上述过程中未替换首节点的指向节点 这里首节点将成为尾节点 所以指向null
head.next = null;
// 因为循环的条件是cur是否为null 如果cur为null 那 pre将是原来链表的尾节点
// 就是逆转后的首节点
return cur;
}

方法二:递归

public Node recursionNode(Node head) {
if (head == null || head.next == null) {
return head;
}
// head 1 2 3 4
Node node = reverseNode(head.next);
// 展示顺序 head 4 3 2 1 // 第一轮:
// 当前指向顺序 4 -> 5 head.next.next = head; // 变成了 5 -> 4 但是4的指针仍然指向5 也就是双向的
// 所以 4 -> null 变成单向
head.next = null; // node是最后一个元素 5 也就是逆转后的 第一个元素
return node;
}

更多文章查看个人博客 个人博客地址:逆转单向链表

最新文章

  1. SQL Server相关书籍
  2. UITableViewCell单元格的删除、插入、移动
  3. Android教程收集贴
  4. RecycleView 实现多布局
  5. ruby 基础知识三 读写文件
  6. --with-http_realip_module选项(后台Nginx服务器记录原始客户端的IP地址 )
  7. [Android Tips] 10. Pull out /data/data/${package_name} files without root access
  8. AFHTTPClient的异步回调模式
  9. linux java cpu 100%
  10. Drbd 安装配置
  11. PHP获取客户端和服务器端IP
  12. 简单使用NSURLConnection、NSURLRequest和NSURL
  13. Python初学
  14. .net core2.0通过entityframework访问Sqlserver数据库
  15. Data_r_and_w(csv,json,xlsx)
  16. KVM虚拟化概述与安装
  17. 理论篇-MySQL知识汇总
  18. (13)UniquePathIII
  19. log4net.Layout.PatternLayout 用 conversion 模式格式化日志事件【翻译】
  20. 20155305《网络对抗》PC平台逆向破解(二)

热门文章

  1. luogu 3702 [SDOI2017]序列计数 矩阵乘法+容斥
  2. vue 的 watch 如何在初始化时执行
  3. PHP全栈学习笔记30
  4. Python里面如何实现tuple和list的转换?
  5. 20191024-6 Alpha发布用户使用报告
  6. 导入项目后,http://schemas.android.com/apk/res/android报错
  7. 上传图片获取base64编码、本地预览
  8. 有关Python的import...和from...import...的区别
  9. iOS12 中的后台下载与上传
  10. ISO/IEC 9899:2011 条款6.4.8——预处理数字