反转链表

LCR 024. 反转链表 - 力扣(LeetCode)

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

img

1
2
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

img

1
2
输入:head = [1,2]
输出:[2,1]

示例 3:

1
2
输入:head = []
输出:[]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?

image-20221109154222124

直接交换法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){//头节点为空或只有一个节点,直接返回
return head;
}
ListNode pre = null;
ListNode cur = head;
ListNode temp = null; //保证遍历不断链
while(cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
head = pre;
return head;
}
}

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(null, head);
}

private ListNode reverse(ListNode pre, ListNode cur) {
if (cur == null) {
return pre;
}
ListNode temp = null;
temp = cur.next;// 先保存下一个节点
cur.next = pre;// 反转
// 更新pre、cur位置
// pre = cur;
// cur = temp;
return reverse(cur, temp);
}
}

头插法(带头节点)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){//头节点为空或只有一个节点,直接返回
return head;
}
ListNode dummy = new ListNode(-1);//虚拟头节点
dummy.next = head;
ListNode cur = head.next;
head.next = null;//头节点变尾结点
ListNode temp = null;
while(cur != null){
temp = cur.next;
cur.next = dummy.next;
dummy.next = cur;
cur = temp;
}
return dummy.next;
}
}

反转链表
http://example.com/2023/05/26/算法/链表/1. 反转链表/
作者
PALE13
发布于
2023年5月26日
许可协议