leetcode 剑指 Offer 18. 删除链表的节点

题目要求

给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

返回删除后的链表的头节点。

解题思路

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def deleteNode(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        # 头节点的值是否等于val
        while head and head.val == val:
            return head.next
        # 构建pre节点,cur节点
        pre = head
        if pre.next is not None:
            cur = pre.next
        else:
            # 若链表只有一个节点head,且其值不等于val,则直接返回head节点
            return head
        # 一般情况
        while cur:
            if cur.val == val:
                pre.next = cur.next
                break
            pre = cur
            cur = cur.next
        return head

猜你喜欢

转载自blog.csdn.net/qq_40317204/article/details/114108620