Day3:Leetcode-206. Reverse Linked List

In a linknode list,we define a = list(),then we add some nodes,if we write a[0].next = a[1], that's fine ,it works, but when we turn to a[1].next = a[0],it time exceed,which confused me a lot.

But finally  I solved it. because,if we say a[1].next = a[0]. At the beginning we already have a[0].next = a[1] ,but we wrote a[1].next  = a[0],it makes a circle, so time limit exceed. 

Solution 1 

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head:
            return None
        a = list()
        cur = ListNode(0,head)
        while head:
            a.append(head)
            head = head.next

        for i in range(len(a)-1,-1,-1):
            if i!=0:
                a[i-1].next = None
                a[i].next = a[i-1]
            else:break
       
        return a[len(a)-1]

Solution 2

Recursion: we can come apart  this quesion,for instance, we are now at the point "2",we've already reversed the numbers after "3" ,that is  5->4->3,for next step,we need to make "3".next into "2". so we have 2.next.next  = 3.

From a macro point of view,what we want,is just go to the end,make them reverse one by one,so I choose recursion,to achieve my goal. 

reverse(head->next) ,until the end ,then traceback,make reversion one by one.

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值