【发布时间】: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