反转单链表

方法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
posted @ 2020-06-25 16:47  guguda  阅读(101)  评论(0)    收藏  举报