我正试图为链表编写代码,以便它删除链表中的节点,它可以是除链表中的第一个和最后一个节点外的任何节点。我在下面提出了一些想法。
我不确定如何完成它,我知道在while循环中需要一些对k的引用,以便我们在遍历链表时跳过节点,但是我如何引用这个k?我要不要做一个'for I in range k',然后在第k次迭代时执行跳跃?
def delete_middle(l1,k):
if l1.head is None:
return None
current = l1.head
while current:
if current == k:
current.next = current.next.next
current = current.next
return head
node.value = node.next.value
node.next = node.next.next
如果您想要删除k为整数的第k个节点,您可以这样做:
def delete_middle(l1,k):
if (l1.head is None) or (k == 0) or (k == find_length(l1) - 1): # second condition checks if k is the first value and the third condition checks if k is the last value which you didn't want to remove.
return None
n = 0 # index counter for the values in the linked list
head = l1.head
current = head
while current is not None:
if n + 1 == k: # check if the next node is the node that you want to remove
current.next = current.next.next
break
current = current.next
n += 1
return head
def find_length(l1): # to returns the length of the linked list
curr = l1.head
n = 0
while curr is not None:
curr = curr.next
n += 1
return n
另外,我建议定义一个链表类,里面有这样的方法,这样你就不必关心在更新链表时返回任何值,除非发送了一个无效的值。