leetcode_206 反转链表

105 阅读1分钟

要求

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。  

示例 1:

image.png

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

image.png

输入:head = [1,2]
输出:[2,1]

示例 3:

输入:head = []
输出:[]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000  

进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?

核心代码

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 is None or head.next is None:
            return head
        p = head
        d = {}
        i = 0
        while p:
            d[i] = p
            p = p.next
            i += 1
        l = len(d)
        for i in range(l-1,0,-1):
            d[i].next = d[i - 1]
        d[0].next = None
        return d[l - 1]

另一解法

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 is None:
            return None 
        cur = head
        pre = None
        nxt = cur.next
        while nxt:
            cur.next = pre
            pre = cur
            cur = nxt
            nxt = nxt.next
        cur.next = pre
        head = cur
        return head

image.png

解题思路:第一种解法:我们先循环使用字典记录下来链表的下标和节点的关系,然后我们反向遍历字典,将一个节点进行拼接,最终在头节点上补上个None,完成反转的过程。第二种解法:我们使用两个指针,一个记录后一个节点信息,另一个完成反向链接,比较好用。