当先锋百科网

首页 1 2 3 4 5 6 7

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

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

解法:

代码:

# 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:
        #若该链表为空,直接返回即可
        if head == None:
            return head
        #定义2个指针
        pre = None
        cur = head
        while True:
            #保存cur的下一个节点地址
            temp = cur.next
            #开始反转
            cur.next = pre
            #开始移动pre与cur---注意这2个顺序不能变
            pre = cur
            cur = temp
            if cur == None:
                break
        return pre