| 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
| 题解
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
"""
解题思路:
1.新建一个头指针
2.遍历head链表,依次在新的头节点位置插入,达到反转的效果
"""
def reverseList(self, head: ListNode) -> ListNode:
# 循环
new_head = None
while head:
per = head.next # pre 为后置节点,及当前节点的下一个节点
head.next = new_head # 插入头节点元素
new_head = head # 把串起来的链表赋值给头指针
head = per # 向后移一个单位
return new_head # 返回一个新的链表