zoukankan      html  css  js  c++  java
  • LeetCode 206. 反转链表

    206. 反转链表

    Difficulty: 简单

    反转一个单链表。

    示例:

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

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

    Solution

    这是一道最容易被考察的题目,迭代和递归的解法都需要掌握,遇到这个题目一定要稳住啊,最好能把两种解法都解释清楚。

    一、迭代版本

    # 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:
            res = None
            while head:
                next = head.next
                head.next = res
                res = head
                head = next
            return res
    

    二、递归版本的解法跟迭代的思路差不多。

    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            return self.helper(head, None)
            
        def helper(self, head, res):
            if not head:
                return res
            next = head.next
            head.next = res
            return self.helper(next, head)
    
  • 相关阅读:
    Fibonacci Again
    N的10000的阶乘
    HDU2141(二分搜索)
    POJ2366(HASH法)
    10106 Product
    UVA 401 Palindromes
    UVA424 Integer Inquiry
    POJ2503(二分搜索)
    mysql重置root密码
    tidb安装haproxy负载均衡
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14136039.html
Copyright © 2011-2022 走看看