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

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

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

思路1:两个指针

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteNode(self, head: ListNode, val: int) -> ListNode:
        if head.val == val:
            return head.next
        left, right = head, head.next
        while right.val != val:
            right = right.next
            left = left.next
        if right:
            left.next = right.next
        return head

思路2:一个指针

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteNode(self, head: ListNode, val: int) -> ListNode:
        if head.val == val:
            return head.next
        right = head
        while right.next and right.next.val != val:
            right = right.next
        if right:
            right.next = right.next.next
        return head
posted @ 2022-03-17 09:30  小Aer  阅读(1)  评论(0编辑  收藏  举报  来源