python_leetcode_206_反转链表_图解

代码

# 206.反转链表

# python双指针法
# 一定要多写几遍
# 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:
        cur = head  # 继承当前的链表
        pre = None  # 设置一个为None的pre指针
        while cur != None:  # 也就是说当cur变成None之后,说明所有节点都更改了方向了

            temp = cur.next  # 保存除头节点外后续的链表至临时值,因为马上要对cur.next进行赋值更改
            cur.next = pre  # 开始新的链表,初始值为pre,即None
            pre = cur  # pre的使命完成之后被赋值为当前的cur链表
            cur = temp  # 当时保存的那个临时链表变成了cur
        return pre

图解

整体思路是将链表不断的插下头部,然后顶在前面的过程

python_leetcode_206_反转链表_图解_第1张图片

python_leetcode_206_反转链表_图解_第2张图片

 

你可能感兴趣的:(链表,leetcode,算法)