单链表反转

阅读 82

2022-02-13

描述

给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。

class Solution:
    def ReverseList(self , head: ListNode) -> ListNode:
        # write code here
        if not head:    # 如果为空
            return head
        a, a.next, b =head, None, head.next     # 初始化
        while b:
            b, a, a.next = b.next, b, a         # 遍历
        return a
输入 {1,2,3} 得到{3,2,1}

解释

if not head 为head链表为空时,直接返回本身
初始化:a = head, a.next=none, b=1
此时 b存在则: b= 2, a=1, a.next = head
此时b存在则: b= 3, a=2, a.next =1
此时b存在则: b=none, a = 3, a.next = 2
此时b为none不存在while循环结束,返回a {3,2,1}

精彩评论(0)

0 0 举报