206. 反转链表


给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

输入:head = [1,2]
输出:[2,1]

递归:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        def backStack(node):
            if not node or not node.next:
                return node
            next = node.next
            ret=backStack(next)
            next.next = node
            node.next = None
            return ret

        return backStack(head)

迭代:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur = head
        pre = None
        while cur:
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next
        return pre
  • 作者:低调做个路人 (扫码联系作者)
  • 发表时间:2021-08-21 03:47:52
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 评论