反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
迭代法
# 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:
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
执行用时:44 ms, 在所有 Python3 提交中击败了76.62%的用户
内存消耗:14.6 MB, 在所有 Python3 提交中击败了72.61%的用户
递归法
# 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 and head.next):
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
执行用时:44 ms, 在所有 Python3 提交中击败了76.62%的用户
内存消耗:18.6 MB, 在所有 Python3 提交中击败了5.12%的用户