image.png
解法
/**
* 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) {
if (head == null) {
return head;
}
// 之前已经反转过的链表的位置
ListNode pre = null;
while (head != null) {
// 维护后一个节点的位置
ListNode next = head.next;
// 当前节点的next指向之前已经反转好的链表
head.next = pre;
// pre指针后移
pre = head;
// 继续遍历
head = next;
}
return pre;
}
}
网友评论