LeetCoded第206题题解--反转链表
2024-09-06 23:24:05
反转一个单链表。
示例
输入: 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;
}
最新文章
- python学习03——设计,与input有关
- 【原】css实现两端对齐的3种方法
- windows7-SQLyog 安装图解
- r-cnn学习(一)
- redis-persist上线
- HTML6 展望
- HDU 2852 KiKi's K-Number(离线+树状数组)
- 第一个jave程序-helloworld
- Web前端一种动态样式语言-- Less
- echarts雷达图
- PHP session 失效不传递的解决办法
- Mac OS X Yosemite安装Hadoop 2.6记录
- log4j - 输出格式控制, PatternLayout参数含义以及详细配置
- 竖倾斜ScrollView
- 1 CRM
- Python复习笔记(二)变量进阶
- bzoj3196 二逼平衡树
- Installing .NET Core on Ubuntu-摘自网络
- c# extern 关键字
- lintcode 刷题记录··