反转一个单链表。

示例
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

方法一:递归

自始至终每个递归返回的都应该是最后一个节点,每次递归将head.next指向head

代码

	public static ListNode reverseList(ListNode head) {
if (head==null||head.next==null){
return head;
}
ListNode listNode = reverseList(head.next);
head.next.next=head;
head.next=null;
return listNode;
}

方法二:迭代

使用三个指针,pre指向前一个节点,cur指向当前节点,next指向下一个节点,让cur指向pre,并向后循环操作

    public static ListNode reverseList2(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur!=null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}

最新文章

  1. python学习03——设计,与input有关
  2. 【原】css实现两端对齐的3种方法
  3. windows7-SQLyog 安装图解
  4. r-cnn学习(一)
  5. redis-persist上线
  6. HTML6 展望
  7. HDU 2852 KiKi's K-Number(离线+树状数组)
  8. 第一个jave程序-helloworld
  9. Web前端一种动态样式语言-- Less
  10. echarts雷达图
  11. PHP session 失效不传递的解决办法
  12. Mac OS X Yosemite安装Hadoop 2.6记录
  13. log4j - 输出格式控制, PatternLayout参数含义以及详细配置
  14. 竖倾斜ScrollView
  15. 1 CRM
  16. Python复习笔记(二)变量进阶
  17. bzoj3196 二逼平衡树
  18. Installing .NET Core on Ubuntu-摘自网络
  19. c# extern 关键字
  20. lintcode 刷题记录··

热门文章

  1. vite插件-自动生成vue组件文档
  2. python + pytest基本使用方法(参数化)
  3. spring的属性注入和构造器注入
  4. python读取csv,Excel,Txt,Yaml 文件
  5. vue3源码难学,先从petite-vue开始吧
  6. (Opencv07)绘制边框
  7. JS对DOM的操作优化法则
  8. chanakya
  9. 除了Swagger UI,你还能选择 IGeekFan.AspNetCore.RapiDoc
  10. noip模拟测试16