【发布时间】:2023-04-06 12:34:01
【问题描述】:
我正在阅读《Cracking the Coding Interview》和做练习题,但我被困在这个问题上:
“实现一个算法来删除中间的节点(即除第一个和最后一个节点之外的任何节点,不一定是确切的中间)或单链表,只允许访问该节点。
示例 输入:链表中的节点 a->b->c->d->e->f 结果:什么都没有返回,但是新的链表看起来像 a->b->d->e->f"
这是我的代码:
class Node:
def __init__(self, data = None, nextnode = None):
self.data = data
self.nextnode = nextnode
def __str__(self):
return str(self.data)
class LinkedList():
def __init__(self, head = None):
self.head = head
def insert(self, data):
new_node = Node(data)
new_node.nextnode = self.head
self.head = new_node
def remove(self, data):
current = self.head
absent = True
if current == None: print('List is empty')
if current.data == data:
self.head = current.nextnode
absent = False
while current.nextnode:
if current.nextnode.data == data:
absent = False
if current.nextnode.nextnode:
current.nextnode = current.nextnode.nextnode
else: current.nextnode = None
else: current = current.nextnode
if absent: print('Element not in list')
def size(self):
current = self.head
size = 0
while current:
current = current.nextnode
size += 1
return size
def find(self, data):
current = self.head
if current == None: print('List is empty')
search = True
while current and search:
if current.data == data:
print(current)
search = False
current = current.nextnode
if search: print('Not found')
def print_list(self):
current = self.head
while current:
print(current, end = ' ')
current = current.nextnode
print('')
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node1.nextnode = node2
node2.nextnode = node3
node3.nextnode = node4
list1 = LinkedList(node1)
list1.insert(2 ****EDITED node2 to 2 here****)
print_list(list1)
def delmid(ll, n):
current = ll.head
if current == n:
print('Can\'t delete first node')
return
while current.nextnode:
if current.nextnode == n:
if current.nextnode.nextnode:
current.nextnode = current.nextnode.nextnode
return
else:
print('Can\'t delete last node')
return
delmid(list1, node2)
print_list(list1)
我不明白为什么它似乎不认为 ll.head 和 node2 是相同的......如果我去掉 list1.insert(node2) 这条线,它确实有效......
我不明白...
编辑:在阅读了书中解决方案的第一句话之后,显然我还是做错了......“只允许访问该节点”意味着你不知道列表的头部......返回到绘图板...
【问题讨论】:
标签: python algorithm linked-list nodes