Python 从链接列表中删除节点
我想创建一个delete_node函数,将列表中位置处的节点作为第一个节点的计数删除。到目前为止,这是我的代码:Python 从链接列表中删除节点,python,linked-list,Python,Linked List,我想创建一个delete_node函数,将列表中位置处的节点作为第一个节点的计数删除。到目前为止,这是我的代码: class node: def __init__(self): self.data = None # contains the data self.next = None # contains the reference to the next node class linked_list: def __init__(self):
class node:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class linked_list:
def __init__(self):
self.cur_node = None
def add_node(self, data):
new_node = node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the 'previous' node.
self.cur_node = new_node # set the current node to the new one.
def list_print(self):
node = ll.cur_node
while node:
print node.data
node = node.next
def delete_node(self,location):
node = ll.cur_node
count = 0
while count != location:
node = node.next
count+=1
delete node
ll = linked_list()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.list_print()
在Python中,您不应该逐字删除节点。如果没有任何东西指向该节点(或者更准确地说,在Python中,没有任何东西引用它),它最终将被虚拟机销毁 如果
n
是一个节点,并且它有一个。next
字段,则:
n.next = n.next.next
有效地丢弃n.next
,使n
的.next
字段指向n.next.next
。如果n
是要删除的节点之前的节点,这相当于在Python中删除它
[p.S.最后一段可能会有点混乱,直到你在纸上画出它-然后它应该变得非常清楚]Python列表是链接列表
thelist = [1, 2, 3]
# delete the second
del thelist[2]
这里有一个方法
def delete_node(self,location):
if location == 0:
try:
self.cur_node = cur_node.next
except AttributeError:
# The list is only one element long
self.cur_node = None
finally:
return
node = self.cur_node
try:
for _ in xrange(location):
node = node.next
except AttributeError:
# the list isn't long enough
raise ValueError("List does not have index {0}".format(location))
try:
node.next = node.next.next # Taken from Eli Bendersky's answer.
except AttributeError:
# The desired node is the last one.
node.next = None
您没有真正使用del
(这让我在这里绊倒,直到我回来再次查看它)的原因是,它所做的只是删除调用它的特定引用。它不会删除对象。在CPython中,一个对象一旦没有更多的引用就被删除。那时候这里发生了什么
del node
运行时,有(至少)两个对节点的引用:我们正在删除的名为node
的引用和上一个节点的next
属性。因为上一个节点仍在引用它,所以实际对象不会被删除,列表也不会发生任何更改
def remove(self,data):
current = self.head;
previous = None;
while current is not None:
if current.data == data:
# if this is the first node (head)
if previous is not None:
previous.nextNode = current.nextNode
else:
self.head = current.nextNode
previous = current
current = current.nextNode;
假设链表有多个节点。例如n1->n2->n3,您希望删除n2
如果你想删除n1,哪一个是头部
我使用递归函数来实现pop()函数,因为引用的迭代方式不太好。代码如下。我希望这对你有帮助!;)
类节点:
定义初始化(self,data=0,next=None):
self.data=数据
self.next=下一个
定义(自我):
返回str(self.data)
类链接列表:
定义初始化(自):
自身。\头部=无
self.\uu tail=无
自身大小=0
def addFront(自身、数据):
newNode=节点(数据、自身头)
if(self.empty()):
self.\uu tail=newNode
self.\uuu head=newNode
自身大小+=1
定义(自我):
#returno-deve-ser-uma字符串:
s=“[”
节点=self.\u头
while节点:
s+=str(node.data)+''如果node.next!=None-else str(node.data)
node=node.next
返回s+“]”
def_u_recPop(self、no、i、index):
如果(i==索引-1):
如果(索引==self.size()-1):
self.\uu tail=否
尝试:
no.next=no.next.next;
除属性错误外:
否。下一个=无
其他:
self.\uu recPop(编号next,i+1,索引)
def pop(自身,索引=0):
如果(索引<0或索引>=self.\u大小或self.\u大小==0):
返回
如果(索引==0):
尝试:
self.\uu head=self.\uu head.next
除属性错误外:
自身。\头部=无
self.\uu tail=无
其他:
self.\u recPop(self.\u头,0,索引)
自身大小-=1
def前(自):
返回self.\u head.data
def返回(自我):
返回self.\u tail.data
def加载回(自身、数据):
newNode=节点(数据)
如果(不是self.empty()):
self.\uuu tail.next=newNode
其他:
self.\uuu head=newNode
self.\uu tail=newNode
自身大小+=1
def为空(自我):
返回self.\uu size==0
def大小(自身):
返回自身大小
定义递归变量(self,No):
如果否==无:返回
self.\uu递归变量(否,下一个)
打印(否,结束=“”)如果是自无其他打印(否,结束=“”)
def倒档(自动):
打印('[',结束='')
自我递归翻转(自我头部)
打印(']')
好的,那么你的问题是什么?向StAcQuoLoT问一些具体问题——不要只给我们一些代码,并说“我想做的事情”。例如,你遇到了什么问题?我理解C++中的算法,IM的问题是如何删除节点对象?基本上与创建新的_node@lost_with_coding如果您理解“在C++中”的算法,那么您就不理解该算法。你知道如何在C++中实现它。如果您理解了该算法,那么您会问一个关于python语法的特定问题。@aaronastering确切地说,破坏node@lost_with_coding在Python中没有销毁对象的想法。当对象不再被引用时,垃圾收集过程会自动执行此操作。但是,Python是比C++更高级的语言,你不需要自己实现这个列表。它已经存在了:list()是的,不需要用Python构建链表。它们已经在语言核心中提供了。Python列表不是链表。具体来说,它们没有任何前进到下一个元素的方法,并且是可索引的;i、 next();i、 next();el3=thelist[3]@Keith,这是一个迭代器。列表是一个iterable,意味着您可以从中构造迭代器。即使使用i=iter(list_)
,它的next
方法也是返回元素,而不是节点。那就是如果我不能做e=I.next();e2=e.next()
。它们是两种不同的东西。我同意链表在python中是愚蠢的,但你的答案实际上是不正确的。我知道,但我这样做是为了练习,虽然你是正确的,但这不是我当前问题所需要的。在这之后,你如何连接这两个部分?@Keith you't,请阅读他所写的“我真的会称之为修剪,因为它是r。”
n1.next = n1.next.next
n2.next = None
head = n1.next
n1.next = None
# Creating a class node where the value and pointer is stored
# initialize the id and name parameter so it can be passed as Node(id, name)
class Node:
def __init__(self, id, name):
# modify this class to take both id and name
self.id = id
self.name = name
self.next = None
# Create a class linkedlist to store the value in a node
class LinkedList:
# Constructor function for the linkedlist class
def __init__(self):
self.first = None
# This function inserts the value passed by the user into parameters id and name
# id and name is then send to Node(id, name) to store the values in node called new_node
def insertStudent(self, id, name):
# modify this function to insert both id and names as in Q1
new_node = Node(id, name)
new_node.next = self.first
self.first = new_node
# We will call this function to remove the first data in the node
def removeFirst(self):
if self.first is not None:
self.first = self.first.next
# This function prints the length of the linked list
def length(self):
current = self.first
count = 0
while current is not None:
count += 1
current = current.next
return count
# This function prints the data in the list
def printStudents(self):
# modify this function to print the names only as in Q2.
current = self.first
while current is not None:
print(current.id, current.name)
current = current.next
# This function lets us to update the values and store in the linked list
def update(self, id):
current = self.first
while current is not None:
if (current.id == id):
current.id = current.id.next
# print(current.value)
current = current.next
# This function lets us search for a data and flag true is it exists
def searchStudent(self, x, y):
current = self.first
while current is not None:
if (current.id == x and current.name == y):
return True
current = current.next
# This function lets us delete a data from the node
def delStudent(self,key):
cur = self.node
#iterate through the linkedlist
while cur is not None:
#if the data is in first node, delete it
if (cur.data == key):
self.node = cur.next
return
#if the data is in other nodes delete it
prev = cur
cur = cur.next
if (cur.data == key):
prev.next = cur.next
return
# Initializing the constructor to linked list class
my_list = LinkedList()
# Adding the ID and Student name to the linked list
my_list.insertStudent(101, "David")
my_list.insertStudent(999, "Rosa")
my_list.insertStudent(321, "Max")
my_list.insertStudent(555, "Jenny")
my_list.insertStudent(369, "Jack")
# Print the list of students
my_list.printStudents()
# Print the length of the linked list
print(my_list.length(), " is the size of linked list ")
# Search for a data in linked list
if my_list.searchStudent(369, "Jack"):
print("True")
else:
print("False")
# Delete a value in the linked list
my_list.delStudent(101)
# Print the linked list after the value is deleted in the linked list
my_list.printStudents()