[英]Delete a Node in the Middle of a linked list, Given only access to that Node. - Python
I am trying delete the middle node, but when I call the function and try to get hold of second node after the given node, it appears to be None. 我正在尝试删除中间节点,但是当我调用该函数并尝试在给定节点之后获得第二个节点的所有权时,它似乎是None。 Below is my code, please help me correct it. 以下是我的代码,请帮助我更正它。
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data= data
self.next= None
class LinkedList():
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def insert(self, data):
node = Node(data)
node.next=self.head
self.head = node
# Function to print elements of the linked list
def printlist(self):
current = self.head
while current:
print current.data
current = current.next
def deleteMiddle(self, node):
second = node.next
print second.data
if node is None:
return
node.data = second.data
node.next = second.next
llist = LinkedList()
llist.insert(10)
llist.insert(15)
mid = Node(20)
llist.insert(mid.data)
llist.insert(16)
llist.insert(17)
llist.insert(19)
print "Before deleting middle or any node"
llist.printlist()
print "After deleting middle or any node"
llist.deleteMiddle(mid)
llist.printlist()
Update 1 : I have added below changes, and it is working fine. 更新1 :我添加了以下更改,并且工作正常。 But want to know, if it is correct and can be (insert and addNode function) combined into one function. 但要知道,是否正确并且可以将(插入和addNode函数)组合为一个函数。 Also I want to understand better way to write this code, as there can be a case, where I want to delete any node and will have access to that node only. 我还想了解编写此代码的更好方法,因为在某些情况下,我想删除任何节点,并且只能访问该节点。 With my code, I am defining node and then deleting it, but I still feel there should be better approach than my code. 使用我的代码,我先定义节点然后删除它,但是我仍然觉得应该有比我的代码更好的方法。
def addNode(self, node):
node.next = self.head
self.head = node
llist.addNode(mid)
You did not actually insert your mid
node into the linked list; 您实际上并未将mid
节点插入链接列表; instead, you inserted a brand new node into the list with the same data value. 相反,您将具有相同数据值的全新节点插入到列表中。 Nothing you do via mid
will have any effect on your list, as it has no connection to the list. 通过mid
进行的任何操作都不会对列表产生任何影响,因为它与列表没有任何关系。
Right off the bat, it looks like you are adding the data from your middle node mid
, rather than the node itself into the head position. 马上,您似乎正在从中间节点mid
而不是节点本身将数据添加到头部位置。 When you try to delete mid
, you need to find the node in the linked list that looks like mid
since it is not the exact same node. 当您尝试删除mid
,您需要在链接列表中找到看起来像mid
的节点,因为它不是完全相同的节点。
Alternatively, you can choose to add your Node
called mid
, by creating a new insert function that takes a Node
instead of data
. 另外,您可以选择添加一个名为mid
的Node
,方法是创建一个使用Node
而不是data
的新插入函数。
ie, def insert(self, node):
即def insert(self, node):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.