这几天写算法的时候碰到这个坑了好长时间的题,第一次自己写出来了,做一个记录
思路
长度为1,2时单独处理
长度大于等于三时:
简单画了一下,看个意思
更详细的解答看
https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/solution/fan-zhuan-lian-biao-by-leetcode-solution-jvs5/
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head==None:
return None
if head.next==None:
#Only one node
return head
elif head.next.next==None:
head.next.next=head
tmp=head.next
head.next=None
return tmp
else:
#递归reverse
front=head
aft=head.next
tod=aft.next
#reverse
head.next=None
while aft!=None:
aft.next=front
front=aft
aft=tod
if tod:
tod=tod.next
return front
Tips
- 记得把
head->next
置None
,防止死循环 - 处理好边缘情况下
tod
的变化,注意None
是没有next
属性的. - 循环跳出条件是
aft==None