

核心代码模式
# 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
prev = None
curr = head
while curr :
nxt = curr.next #暂存下一个节点
curr.next = prev #反转指针
prev = curr #反转指针
curr = nxt #curr前进
return prev

测试示例
#构造链表 1->2->3
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
sol = Solution()
new_head = sol.ReverseList(head)
#打印反转后的链表
res = []
while new_head:
res.append(new_head.val)
new_head = new_head.next
print(res)

被折叠的 条评论
为什么被折叠?



