概念:

HashMap Node 节点,Node节点有自身的值和 next 指向:
//HashMap Node 部分源码
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}LinkedList Node 结点使用双链表
//LinkedList 部分源码
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
单链表的反转就是把链表的指向换一个方向,由从左往右变成从右变左。
主要解题思路是拆分每一个指针。

上图从 1 指向 2 变成 2 指向1,也就是需要设置 2 节点的next = 1,在做指向的改变之前要先将 2 节点的 next 存起来,然后改变 2 节点的next:

Java 解题代码:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
// 创建一个空链表
ListNode node= null;
while(cur != null) {
// 存储 next
ListNode next = cur.next;
// 当前链表指向指向新的链表
cur.next = node;
// 当前节点赋值给 node
node = cur;
// 遍历下一个节点
cur = next;
}
return pre;
}
}