小言_互联网的博客

LeetCode-Python-206.反转链表

352人阅读  评论(0)

题目描述:
反转一个单链表。

示例:

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

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思路:
迭代

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        new_head = None
        while head :     
            tmp = head.next      # 备份原来head节点的next地址
            head.next = new_head
            new_head = head
            head = tmp
        
        return new_head

递归

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        start = self.reverseList(head.next)
        head.next.next = head 
        head.next = None
        return start

转载:https://blog.csdn.net/Dawn510/article/details/102490969
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场