删除链接列表中的节点,只允许访问该节点

Delete a Node in Linked list given access to only that Node

我正在应对这个代码挑战:

Delete a Node in Linked list given access to only that Node

A linked list is a collection of nodes. Where each node contains some data address of the next node, if it is the last node then it contains the data only. This way we can access all the nodes if we have the address of first node.

Now the task is that given a pointer to some node in a linked list, delete it if it is not the last node of the list.

Complete the function deleteNodeK() which takes the address of the node of a linked list as a parameter and delete this node from the list. (If given node is last node of list then do nothing.)

我试图通过将 node.next 数据复制到当前节点数据然后将当前节点的指针更改为 node.next.next 来删除节点。

def deleteKNode(node):
  if node.next == None:
    return
  else:
    node.data = node.next.data
    node.next = node.next.next

但是它给我以下错误:

if node.next == None:
AttributeError: 'NoneType' object has no attribute 'next'

下面是我的完整代码片段:

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

def printList(node):
  while (node != None):
    print(node.data, end=' ');
    node = node.next;
    
def insertEnd(head, data):
  new_node = Node(data)
  if head is None:
    head = new_node
    return head;
    
  last = head
  while (last.next):
    last = last.next
    
  last.next =  new_node
  return head

def deleteKNode(node):
  if node.next == None:
    return
  else:
    node.data = node.next.data
    node.next = node.next.next


# Don't edit this function
def main():
    t = int(input().strip());
    for i in range(t):
      head = None;
      n = int(input().strip());
      k = 0;
      if(n!=0):
        inp = input().strip().split();
        for j in inp:
          head = insertEnd(head,int(j.strip()));
      k = int(input().strip());
      node = head;
      if(k>0):
        while(k>0):
          node = node.next;
          k = k-1;
      deleteKNode(node);
      printList(head);
      print();

if __name__ == "__main__":
  main();

错误消息表明 deleteKNode 是使用 None 参数调用的。由于您的主要代码无法更改(根据那里的代码注释),我们必须假设 deleteNode 真的可以用 None.

调用

所以改变你的if条件如下:

def deleteKNode(node):
  if node is None or node.next is None:
    return
  else:
    node.data = node.next.data
    node.next = node.next.next

请注意(在代码挑战中也有解释)当 node 是列表的最后一个节点时,此函数不会删除该节点——也不可能。