一、题目
LeetCode 206题
测试地址:https://leetcode-cn.com/problems/reverse-linked-list/
二、图解
链表基本结构
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
1、方法一
假头(dummy)+头插法+迭代法
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1, null);
while (head != null) {
ListNode tmp = head.next;
head.next = dummy.next;
dummy.next = head;
head = tmp;
}
return dummy.next;
}
}
2、方法一图解
(1)初始链表
(2)while循环内4条语句
(3)第1次循环完后
(4)第2次循环完后
3、方法二
双指针+迭代法
class Solution {
public ListNode reverseList(ListNode head) {
// 定义需要临时保存的节点
ListNode pre = null;
ListNode next = null;
while (head != null) {
// 为了把head的第一个节点拿出来,先把下一个位置保存一下
next = head.next;
// 让当前拿出来的节点指向之前反转好的链表,成为新的pre的第一个节点
head.next = pre;
// 让pre节点指向当前摘出来的节点,这样就指向了整体当前反转的部分
pre = head;
// head指向原链表的下一个,准备把下一个节点拿出来
head = next;
}
return pre;
}
}
4、方法二图解
(1)保存下一个节点、改变head指向、调整pre位置
(2)调整head指向
5、方法三
递归
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 进入下一层进行递归
ListNode newHead = reverseList(head.next);
// 上面保存下来的节点,指向已经逆序好的节点
head.next.next = head;
// 去除之前的关联,打破无限循环
head.next = null;
return newHead;
}
}