假设我们有一个包含很少元素的链表。我们的任务是编写一个函数,该函数将从列表中删除给定的节点。因此,如果列表类似于1→3→5→7→9,并且删除3后,它将是1→5→7→9。
考虑我们有指针'node'指向要删除的节点,我们必须执行以下操作以删除该节点-
node.val = node.next.val
node.next = node.next.next
让我们看下面的实现以更好地理解-
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution(object): def deleteNode(self, node, data): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ while node.val is not data: node = node.next node.val = node.next.val node.next = node.next.next head = make_list([1,3,5,7,9]) ob1 = Solution()ob1.deleteNode(head, 3) print_list(head)
linked_list = [1,3,5,7,9] data = 3
输出结果
[1, 5, 7, 9, ]