【发布时间】:2019-09-08 23:25:38
【问题描述】:
好的,所以我是计算机编程的新手,长话短说,我不想在余生中成为杂货商。我今年 25 岁,正在学习这些概念和 python,所以请善待。
我想使用名为 copyList 的函数将链接列表从 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 对象工作。
【问题讨论】:
标签: python linked-list nodes