【问题标题】:Delete a node in a linked list by using dictionary key使用字典键删除链表中的节点
【发布时间】:2021-02-26 22:57:17
【问题描述】:

我有以下方法,我想从列表中删除{5285831021: 'Hayes'}。只传5285831021怎么办?

class Node:
    def __init__(self, data=None):
        self.data = data
        self.prev = None
        self.next = None

class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insert(self, pair):
        if not isinstance(pair, Node):
            pair = Node(pair)
        if self.is_empty():
            self.head = pair
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = pair
            pair.prev = current
        self.tail = pair

    def __str__(self):
        to_print = ''
        current = self.head
        while current:
            to_print += f'{current.data}<->'
            current = current.next
        if to_print:
            return f'[{to_print[:-3]}]'
        return '[]'

这是我创建的通过给定键删除节点的方法。

    def delete(self, key):
        pass

my_list = DoublyLinkedList()
my_list.insert({2363688062: 'Clark'})
my_list.insert({5598260087: 'Russell'})
my_list.insert({5285831021: 'Hayes'})
my_list.insert({5285234321: 'Henderson'})
my_list.insert({9447143408: 'Hamilton'})

my_list.delete(5285831021)
print(my_list)

【问题讨论】:

  • 您需要先从DoublyLinkedList 中删除Node,然后才能删除它。

标签: python dictionary data-structures linked-list


【解决方案1】:
def delete(self, value):
    curr = self.head
    while curr:
        if list(curr.data.keys())[0] == value:
            node_to_delete = curr.next
            curr.data = node_to_delete.data
            curr.next = node_to_delete.next
            return
        curr = curr.next

【讨论】:

  • 这个编辑的问题是它没有删除链表中的最后一个键。你之前的回答有帮助。如果我不做 del(current) 怎么办?它也可以正常工作,为什么要使用 del 关键字?
  • 很高兴它有帮助,也很抱歉,但我是回答堆栈溢出问题的新手,我想问一下如何从答案中检查以前的编辑(即使不是我的)?
猜你喜欢
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多