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

链表是有方向性的,只要改变了方向,就能做到反转。

cur:表示当前结点。

pre:表示上一个结点。

tmp:用来保存下一个结点防止链表断裂。

在操作时,先保存,再改变指向,最后赋值即可。

python3代码:

# 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:
        pre, cur = None, head
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

LeeCode 206.反转链表插图

作者 admin

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注