LeetCode-剑指 Offer 24. 反转链表

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路1:三指针

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None: return None
        l = head
        r = head.next
        if r is None:   # 链表长度为1,直接返回head
            return head
        temp = r.next
        while temp:
            if temp:  # 如果temp不为空,反转r指针,l,r和temp同时后移
                r.next = l
                l = r
                r = temp
                temp = temp.next
            else:  # 如果temp为空,反转r指针,l指向r
                r.next = l
                l = r
        # 最后temp为空跳出循环,没有修改l,r值
        r.next = l
        l = r
        head.next = None
        return l

优化:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None: return None
        l = head
        r = head.next
        if r is None: 
            return head
        temp = r.next
        while temp:
            r.next = l
            l = r
            if temp:
                r = temp
                temp = temp.next
        r.next = l
        l = r
        head.next = None
        return l

思路2:上面比较好理解,这里其实初始化l指针为空,避免了最后一步head.next = None语句

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None: return None
        l = None
        r = head
        while r:
            temp = r.next
            r.next = l
            l = r
            r = temp
        return l

思路3:递归思想

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        def digui(pre, cur):
            if cur is None:  # 递归找到最后一个结点,cur为None,那么pre就是最后要给结点
                return pre
            res = digui(cur, cur.next)  # 递归最后用res指向尾结点
            cur.next = pre  # 调整cur指针指向前一个结点pre
            return res  # 每次返回尾结点

        return digui(None, head)
posted @ 2022-03-19 12:52  小Aer  阅读(2)  评论(0编辑  收藏  举报  来源