python没有专门的指针概念
定义链表:
# Definition for singly-linked list.
class ListNode(object):
def __init__(self):
self.val = None
self.next = None
递归 :
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None or head.next == None: #链表为空或只有头节点的情况
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
迭代:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
curr = head
while curr:
next = curr.next #在链表反指前一个节点之前,先将当前链表指向一个临时变量,否则链表反指后会断掉
curr.next = pre
pre = curr
curr = next
return pre
比较形象的图解blog: 看图理解单链表的反转_feliciafay的博客-CSDN博客_单向链表反转
python代码: 翻转链表的三种方法(python实现)_the__apollo的博客-CSDN博客_反转链表python