我不想做一个长时间的电脑编程。我今年25岁,正在学习这些概念和python,所以请友好一点。在
我想使用一个名为copyList的函数将LinkedList从一个LinkedList对象复制到另一个对象。它不应该接受除自身之外的任何参数,并且应该在不改变原始列表的同时输出LinkedList的副本。在
我试着查看堆栈,发现了一个类似的代码,但它并没有解决我的问题,因为代码与我的代码相似,但不起作用,因为我尝试打印新的LinkedList,它不包含值,我相信它是空的。我在下面给出了类似的代码:
class Node:
def __init__(self,x):
self.data = x
self.next = None
class LinkedList:
def __init__(self):
self.top = None
def printList(self):
print("top^")
while self.top is not None:
print(self.top.data)
self.top = self.top.next
print("tail^")
def in_list(self, x):
current = self.top
while current is not None:
if current.data is x:
return 1
current = current.next
return 0
def findCellBefore(self, x):
current = self.top
if current is None:
return 0
while current.next is not None:
if current.next.data is x:
current = current.next
return 1
def findCellBeforeSential(self,x):
if (self.top.next is None):
return 0
while (self.top.next is not None):
if (self.top.next.data is x):
return self.top.data
return 1
def add_0(self, newNode):
# i. make next of new node as head.
newNode.next = self.top
# ii. move head to point to new node.
self.top = newNode
def add_end(self, newNode):
current = self.top
if (current is None):
self.add_0(newNode)
return
while (current.next is not None):
current = current.next
current.next = newNode
newNode.next = None
def insertNode(self, after_me, new_cell):
new_cell.next = after_me.next
after_me.next = new_cell
# update prev links.
new_cell.next.prev = new_cell
new_cell.prev = after_me
def deleteAfter(self, after_me):
after_me.next = after_me.next.next
def CopyList(self):#Out put new Linked List that is a copy of current Linked List with out altering it.
# create new LinkedList
newLinkedList = LinkedList()
#current = self.top
#below is from stackoverflow : https://stackoverflow.com/questions/36491307/how-to-copy-linked-list-in-python
#while current.next != None:
# newLinkedList.add_end(current.data)
# current = current.next
#newLinkedList.add_end(current.data)
#return newLinkedList
while self.top is not None:
newNode = Node(self.top.data)
newLinkedList.add_end(newNode)
self.top = self.top.next
return newLinkedList
LIST0 = LinkedList()
node0 = Node(1)
node1 = Node(2)
node2 = Node(3)
LIST0.add_end(node1)
LIST0.add_0(node0)
LIST0.add_0(node2)
node3 = Node(4)
LIST0.insertNode(node2, node3)
LIST0.printList()
LIST1=LIST0.CopyList()
LIST1.printList()
我想让它简单地打印出一个新列表,它是LIST0的副本,并且让LIST1作为LinkedList对象工作。在
我认为这与newLinkedList的创建没有被保存在内存中有关,因为代表您的某种指针错误(也就是说,您需要进一步学习Python(nic)语言)。正在传递,但新节点未保存到newLinkedList中。我也希望看到解决办法。在
问题的很大一部分是:
正常情况下self.top公司指向节点的顶部,除非替换或删除顶部节点,否则不应更改。你要做的基本上就是从列表中删除所有节点。在
注释掉的代码看起来是正确的,除了以下行“newLinkedList.add_结束(当前数据)“不够缩进。Python缩进系统的一个抱怨是,如果代码以改变缩进的方式粘贴,也会改变行的分组。该行应该是循环的一部分,并与上面的行的缩进相匹配。在
看完你的代码后,@johnbayko似乎是正确的,你必须离开self.top公司(哨兵头)独自一人。。。在您的代码中,您似乎有某些函数使用self.top公司out right和其他使用current=self.top公司引用它并在函数内完成相应的工作。函数的顶部指针应该正好是这样的,因为它应该是一个参考(普遍-认为它是“北极星”,供您在导航列表时使用),以供其余代码遵循。在
下面是更正的代码:在此之后理解链表等概念应该更容易些。在
相关问题 更多 >
编程相关推荐