题目
代码
执行用时:36 ms, 在所有 Python3 提交中击败了72.30% 的用户
内存消耗:16.1 MB, 在所有 Python3 提交中击败了34.25% 的用户
通过测试用例:27 / 27
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
stack=[]
while head:
stack.append(head)
head=head.next
if not stack:
return None
ans=stack[-1]
now=ans
stack.pop()
while stack:
temp=stack.pop()
now.next=temp
now=temp
now.next=None
return ans
【方法2:原地,不占用额外空间】
执行用时:40 ms, 在所有 Python3 提交中击败了46.78% 的用户
内存消耗:16.1 MB, 在所有 Python3 提交中击败了36.94% 的用户
通过测试用例:27 / 27
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return None
pre,now=head,head
while now:
if now==pre:
now=now.next
else:
temp_now=now
temp_now_next=now.next
now.next=pre
pre=temp_now
now=temp_now_next
head.next=None
return pre
【方法3:递归法】
执行用时:52 ms, 在所有 Python3 提交中击败了9.41% 的用户
内存消耗:20.6 MB, 在所有 Python3 提交中击败了10.97% 的用户
通过测试用例:27 / 27
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
newHead=self.reverseList(head.next)
head.next.next=head
head.next=None
return newHead
【方法4:递归】
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def recur(cur, pre):
if not cur: return pre # 终止条件
res = recur(cur.next, cur) # 递归后继节点
cur.next = pre # 修改节点引用指向
return res # 返回反转链表的头节点
return recur(head, None) # 调用递归并返回