刷题记录-day3 (删除链表的节点)

慕犹清

关注

阅读 20

2022-02-06

删除链表的节点

在这里插入图片描述

class Solution:
    def deleteNode(self , head: ListNode, val: int) -> ListNode:
        # write code here
        # 最简单的解法,遍历链表,如果遇到要删除的值,就跳过要删除的值,并将它的前后节点相连
        # 只需要排除链表为空和需要删除的在链表头节点两种情况
        result = head
        if not head:
            return None
        if result.val == val:
            return result.next
        while result:
            if result.next.val == val:
                result.next = result.next.next
                break
            result = result.next
        return head

精彩评论(0)

0 0 举报