LeetCode 206 反转单链表 python3

1、迭代

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        # 三个指针,类似于冒泡
        # [1,2,3,4,5]->[2,1,3,4,5]->[3,2,1,4,5]->[4,3,2,1,5]->[5,4,3,2,1]
        if not head or not head.next:
            return head
        cur = head
        pre,temp = head,None
        while cur:
            temp = cur.next
            pre.next = temp
            cur.next = head
            head = cur
            cur = temp
        return head

优化版:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        cur,prev = head,None
        while cur:
            temp = cur.next
            cur.next = prev
            prev = cur
            cur = temp
        return prev

2、递归

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if (head == None or head.next == None):
            return head
        cur = head.next
        newHead = self.reverseList(cur)
        cur.next = head
        head.next = None
        return newHead

 

你可能感兴趣的:(LeetCode)