LeetCode題解(Offer24):反轉連結串列(Python)

長行發表於2020-10-01

題目:原題連結(簡單)

標籤:連結串列

解法時間複雜度空間複雜度執行用時
Ans 1 (Python) O ( N ) O(N) O(N) O ( 1 ) O(1) O(1)56ms (14.20%)
Ans 2 (Python) O ( N ) O(N) O(N) O ( 1 ) O(1) O(1)44ms (77.44%)
Ans 3 (Python)

解法一:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head:
            ans = ListNode(0)
            ans.next = head
            node = head.next
            head.next = None
            while node:
                temp = ans.next
                ans.next = node
                node = node.next
                ans.next.next = temp
            return ans.next

解法二(合併解法一的指標交換):

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head:
            ans = ListNode(0)
            ans.next, node, head.next = head, head.next, None
            while node:
                ans.next, node.next, node = node, ans.next, node.next
            return ans.next

相關文章