[Instant Note] LinklistReverse

这几天写算法的时候碰到这个坑了好长时间的题,第一次自己写出来了,做一个记录

思路

长度为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->nextNone,防止死循环
  • 处理好边缘情况下tod的变化,注意None是没有next属性的.
  • 循环跳出条件是aft==None
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值