Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Xóa nút trong danh sách liên kết Python


Cho danh sách liên kết, xóa nút cho trước. Ví dụ: 1→3→5→7→9, xóa 3 → 1→5→7→9.

Cho con trỏ node đến nút cần xóa, thực hiện:

  • node.val = node.next.val
  • node.next = node.next.next

Ví dụ

Triển khai Python:

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): 
        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, ]