思路:

申请两个指针,第一个指针叫 pre,最初是指向 null 的。

第二个指针 cur 指向 head,然后不断遍历 cur。

每次迭代到 cur,都将 cur 的 next 指向 pre,然后 pre 和 cur 前进一位。

都迭代完了(cur 变成 null 了),pre 就是最后一个节点了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 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;
ListNode cur = head;
while(cur!=null){
ListNode nxt=cur.next;
cur.next=pre;
pre=cur;
cur=nxt;
}
return pre;
}
}

img