题目206. 反转链表 - 力扣(LeetCode)
思路
问题: 链表可以选用迭代或递归方式完成反转。能否用两种方法解决这道题?
方法一:next指针
不用重新定义链表,通过改变next指针指向来完成反转
(图源:代码随想录 (programmercarl.com))
- 初始化pre和cur
//pre作为链表的尾部只能为null
//不要和虚拟头节点一样赋值(0,head)
ListNode pre = null;
ListNode cur = head;
- 先断开cur.next,用tmp保存
- cur.next指向pre
- 更新
pre = cur;cur = tmp
顺序一定一定一定不能颠倒 - 返回反转后的新头节点
return pre
代码
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur != null) {
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
方法二:递归
思路
- 依据双指针写法,一一对应
- 递归函数参数赋值
代码
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(head,null);
}
public ListNode reverse(ListNode cur, ListNode pre) {
if(cur == null) return pre;
ListNode tmp = cur.next;
cur.next = pre;
return reverse(tmp,cur);
}
}