/**
* 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 tmp = head.next; // 暂存后继节点 head.next
head.next = pre; // 修改 next 引用指向
pre = head; // pre 暂存 head
head = tmp; // head 访问下一节点
}
return pre;
}
}
Python实现
python复制代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur, pre = head, None
while head:
# 1.将头结点的下一个节点暂存在temp中
temp = cur.next
# 2.头结点的下一个节点存入pre指针中
cur.next = pre
# 3.pre指针指向头结点,即pre指针永远指向新链表添加节点的位置,而新节点一直随着头结点更新而更新
pre = cur
# 4.将头结点指向一开始存入的下一个节点,起到遍历的作用
cur = temp
# 返回构造的翻转后的新链表
return pre