标签:单链表 one turn 复杂 nod python 链表 方法 def
迭代
时间复杂度:O(n)
空间复杂度:O(1)
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
p = None
cur = head
while cur:
q = cur.next
cur.next = p
p , cur = cur , q
return p
递归
时间复杂度:O(n)
空间复杂度:O(n)
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
cur = self.reverseList(head.next)
head.next.next = head
head.next = None
return cur
标签:单链表 one turn 复杂 nod python 链表 方法 def
原文地址:https://www.cnblogs.com/gugu-da/p/13192158.html