leetcode每日一题 python解法 3月2日

难度:简单

题目内容:

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

题解:

依然比较简单,就是反转一下链表而已

迭代

空间复杂度O(n),时间复杂度O(n)

代码

# 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:
        resHead = ListNode(0)
        L1 = head
        L2 = resHead
        L1list = []
        while not (L1 == None):
            L1list.append(L1.val)
            L1 = L1.next
        for i in range(len(L1list)-1,-1,-1):
            L2.next = ListNode(L1list[i])
            L2 = L2.next
        return resHead.next

递归

空间复杂度O(n),时间复杂度O(n)

代码

# 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:
        if not head or not head.next:
            return head
        else:
            p = self.reverseList(head.next)
            head.next.next = head
            head.next = None
            return p

你可能感兴趣的:(leetcode每日一题 python解法 3月2日)