Day39.反转链表

题目描述:

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

代码如下:

迭代:

class Solution(object):
    def reverseList(self, head):
        fir = head
        sec = None
        thi = None
        while fir != None:
            thi = fir.next
            fir.next = sec
            sec = fir
            fir = thi
        return sec

在这里插入图片描述

递归:

class Solution(object):
    def reverseList(self, head):
      if head.next == None:
            return head
        fir = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return fir

在这里插入图片描述

发布了71 篇原创文章 · 获赞 4 · 访问量 1095

猜你喜欢

转载自blog.csdn.net/qq_44957388/article/details/101769184