给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 力扣地址: https://leetcode.cn/problems/reverse-linked-list/description/
思路就是: 用 cur 遍历链表,逐个节点“掉头”指向 pre,最终 pre 成为新链表的头。 先说一下我们的目标就是:把所有箭头翻转
原链表:1 → 2 → 3 → … → null 期望变成:… ← 3 ← 2 ← 1,并返回新的头(原来的尾) 三根指针各干啥
过程就是: 从 head 开始,用 cur 指针依次走过原链表的每一个节点,把它的 next 指针掉个头,改成指向前一个节点(pre)。
class Solution {
public ListNode reverseList(ListNode head) {
//检测是不是空链表
if(head == null) {
return null;
}
//检测是不是只有一个元素
if(head != null) {
return head;
}
ListNode cur = head;
ListNode pre = new ListNode();
while (cur != null) {
ListNode next = cur.next; // 先存下一个
cur.next = prev; // 反转指向
prev = cur; // 前移 prev
cur = next; // 前移 cur
}
}
return pre;
}在链表里,递归通常有两个关键点:
通俗讲:递归法就是 先把子链表反转好,再让当前节点挂到子链表尾巴后面,层层回溯,完成整个链表反转。
每一层的过程(例子:1 → 2 → 3):从最后一个节点开始转换方向,把链表的方向一层层“倒回来”
最终 newHead = 3,就是新的头。
执行过程(例子:1 → 2 → 3)
最终结果:3 → 2 → 1 → null
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) {
return head;
}
if( head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
//newHead.next = head;
//把当前节点 head 接到它后一个节点(head.next)的后面,实现“反转指针方向”。
head.next = null; // 避免形成环
return newHead;
}
}思想:
新建一个虚拟头 dummy;
每次把原链表的当前节点摘下来,插到 dummy 的后面;
最后 dummy.next 就是反转后的链表。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode dummy = null;
while (head != null) {
ListNode next = head.next; // 取下一个
head.next = dummy; // 插到前面
dummy = head; // 更新新链表头
head = next; // 原链表继续
}
//head为空,所以dummy 返回是为最后的结果
return dummy;
}
}与前文差不多只是叫法不一样思路是一样的,这个比较好理解,就不多说了