首页 > 其他 > 详细

反转单链表

时间:2020-06-25 17:24:18      阅读:54      评论:0      收藏:0      [点我收藏+]

方法1:

迭代

时间复杂度: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

反转单链表

原文:https://www.cnblogs.com/gugu-da/p/13192158.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!