[英]Implementing append function in linked list in python
I am trying to write the list.append() operation in python. 我正在尝试在python中编写list.append()操作。 I implemented a linked list and it work fine.
我实现了一个链表,它工作正常。 But I am not getting the last data item to be printed.
但是我没有得到要打印的最后一个数据项。 When I try to print all the items in the list I get all the data value inside the node printed except the last one.
当我尝试打印列表中的所有项目时,我得到了除最后一个节点外所有已打印节点的数据值。 I get 'None' printed instead of the value.
我打印了“无”而不是值。 I'm making some mistake in assigning the next pointer to 'None' in the newly added node.
在新添加的节点中将下一个指针分配给“ None”时,我犯了一些错误。 Need help in fixing.
需要修复方面的帮助。
Implementation of Node class and List class. 实现Node类和List类。
class Node:
def __init__(self,item):
self.data = item
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newItem):
self.data = newItem
def setNext(self, newNext):
self.next = newNext
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
count = 0
current = self.head
while current != None:
count = count + 1
current = current.getNext()
def append(self, item):
current = self.head
isEnd = False
newItem = Node(item)
while not isEnd:
if current.getNext() == None:
isEnd = True
else:
current = current.getNext()
current = current.setNext(newItem)
newItem = current.getNext()
def printList(self):
current = self.head
isEnd = False
while not isEnd:
if current.getNext() == None:
isEnd = True
else:
print current.getData()
current = current.getNext()
I create an object and pass values. 我创建一个对象并传递值。
mylist = UnorderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
print(mylist.size())
mylist.append(12)
print(mylist.size())
mylist.append(15)
print(mylist.size())
print('\n')
print mylist.printList()
Output is: 输出为:
6
7
8
54
26
93
17
77
31
12
None
The problem is you are doing 问题是你在做什么
print(mylist.printList())
打印(mylist.printList())
while printList() doesn't actually return anything. 而printList()实际上不返回任何内容。 That's the last None printed there.
那是那里最后打印的None。
Hope this helps: 希望这可以帮助:
current = self.head
while(current!=None):
print(current.getData())
current=current.getNext()
This should be placed inside printlist. 这应该放在打印列表中。
And called this way : 并这样称呼:
mylist.printlist()
54
26
93
17
77
31
12
15
Edit : I had also modified your append function to : 编辑:我还修改了您的附加函数为:
def append(self, item):
print("append",item)
current = self.head
isEnd = False
newItem = Node(item)
while not isEnd:
if current.getNext() == None:
isEnd = True
else:
current = current.getNext()
print("\Appending to",current.getData())
current.setNext(newItem)
current=current.getNext()
print("\tAppended",current.getData())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.