如何解决使用字典键删除链表中的节点
我有以下方法,我想从列表中删除 {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)
解决方法
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。