from re import template # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 # @return ListNode类 # class Solution: def ReverseList(self , head: ListNode) -> ListNode: # write code here if head is None: # 先考虑特殊情况 return head p = head # 滑动指针,作用是遍历原链表 new_h = None # 保存翻转后的链表头,最终return此值,跟着p动态刷新 while p is not None: temp = p.next # 先保存指针p下一跳, 防止直接修改后找不到原来的值 # 翻转操作 p.next = new_h # 紧接着,修改当前p指针的下一跳为翻转后链表头 new_h= p # 紧接着,将当前指针p赋给翻转后的链表头。 # 翻转操作完成,这时原链表p1.ext为None,翻转后链表头new_h为p1 p = temp # 更新链表指针 return new_h