day03 代码随想录算法训练营 206. 反转链表

发布时间 2024-01-01 16:58:07作者: 山雨欲來風滿楼

题目:206. 反转链表

我的感悟:

  • 理解cur是什么?
  • 相信自己!!

代码难点:

  • cur = head 可以省略不
  • 每一个步骤里的cur是什么

代码示例:

# 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: Optional[ListNode]) -> Optional[ListNode]:
        # 难点是:要理解cur是什么?
        # cur可以理解为一个实例,由2部分构成,[cur = cur.val + cur.next]
        #     第1个部分是值(cur.val);
        #     第2个部分是下一个数的位置(cur.next)

        pre = None  # 创建空的节点,不断往上挂节点,最终返回一个反转后的链表
        cur = head # 为什么不直接用head? ### 解答: 为了不破坏题目原来的参数,非要写head也可以
        while cur:  # 遍历这个节点
            # 现在的cur是什么?? [cur = 1 + 2的位置]
            tmp = cur.next # 先保存后面的位置
            cur.next = pre  # 更改目前这一个节点的next指向None
            # 注意:问自己此时cur是什么?? [cur  = 1 + None的位置]
            # 此时cur里面有val = 1 ,next = None
            # 把这个新的cur挂到pre上
            pre = cur   # 挂上
            
            # cur已经用完了,可以扔掉了。现在为了循环继续执行,继续利用cur
            cur = tmp
        return pre  # 返回这个新的链表pre

通过截图:

打印cur的调试代码:

# 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
        while cur:
            print("=" * 20)
            print(f"1位置===> cur本身:{cur},cur的值{cur.val},cur的指针{cur.next}")

            temp = cur.next  # 保存一下 cur的下一个节点,因为接下来要改变cur->next
            cur.next = pre  # 反转

            print(f"2位置的===> cur本身:{cur},cur的值{cur.val},cur的指针{cur.next}")

            # 更新pre、cur指针
            pre = cur

            cur = temp

        return pre


# 创建链表节点
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)

# 链接节点构成链表
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5


# 验证链表
# 定义一个函数用于遍历和打印链表
def print_list(node):
    while node:
        print(node.val, end=" -> " if node.next else "\n")
        node = node.next


# 打印初始链表
print("Original list:")
print_list(node1)

# 创建链表和Solution实例
solution = Solution()
reversed_head = solution.reverseList(node1)

# 打印反转后的链表
print("Reversed list:")
print_list(reversed_head)

资料:

题目链接/文章讲解/视频讲解:https://programmercarl.com/0206.%E7%BF%BB%E8%BD%AC%E9%93%BE%E8%A1%A8.html