classSolution(object):defreverseList(self, head):"""
:type head: ListNode
:rtype: ListNode
"""# 申请两个节点,pre和 cur,pre指向None
pre =None
cur = head
# 遍历链表,while循环里面的内容其实可以写成一行# 这里只做演示,就不搞那么骚气的写法了while cur:# 记录当前节点的下一个节点
tmp = cur.next#保存当前节点的下一个节点,方便改变cur.next# 然后将当前节点指向pre
cur.next= pre
# pre和cur节点都前进一位
pre = cur
cur = tmp
return pre
作者:wang_ni_ma
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/dong-hua-yan-shi-206-fan-zhuan-lian-biao-by-user74/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解法二、递归解法[K]
classSolution(object):defreverseList(self, head):"""
:type head: ListNode
:rtype: ListNode
"""defreverse(pre,cur):ifnot cur:return pre
tmp = cur.next
cur.next= pre
return reverse(cur,tmp)return reverse(None,head)