Leetcode 206. Reverse Linked List 链表翻转 Python 两种解法

2021-06-15 15:54:43 浏览数 (1)

问题描述

Reverse a singly linked list. 翻转一个链表

#1

第一种方法:迭代

代码语言:javascript复制
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre = cur = None
        if head:
            pre = head
            cur = head.next
            pre.next = None
        else:
            return None
        while cur:
            p = cur
            cur = cur.next
            p.next = pre
            pre = p
        return pre

#2

第二种方法:递归

代码语言:javascript复制
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def reverseList(self, head):
        return reverse(head)

    def reverse(self, node, prev=None):
        if not node:
            return prev
        n = node.next
        node.next = prev
        return reverse(n, node)

0 人点赞