Giả sử chúng ta có một danh sách liên kết với ít phần tử. Nhiệm vụ của chúng ta là viết một hàm sẽ xóa nút đã cho khỏi danh sách. Vì vậy, nếu danh sách giống như 1 → 3 → 5 → 7 → 9 và sau khi xóa 3, nó sẽ là 1 → 5 → 7 → 9.
Hãy xem xét chúng ta có con trỏ ‘nút’ để trỏ nút đó bị xóa, chúng ta phải thực hiện các thao tác này để xóa nút -
- node.val =node.next.val
- node.next =node.next.next
Ví dụ (Python)
Hãy cùng chúng tôi xem cách triển khai sau đây để hiểu rõ hơn -
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) Đầu vào
linked_list = [1,3,5,7,9] data = 3
Đầu ra
[1, 5, 7, 9, ]