/**
* 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; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
while (head != null) {
ListNode next = head.next; //next 指针用于存储当前遍历节点的下一个节点
head.next = pre; //每次遍历到当前节点,都将其 next 指针指向 pre
pre = head; // pre 前进一位
head = next; // 遍历下一个节点
}
return pre; //遍历结束时,head 为 null, pre 就是最后一个节点
}
}