我觉得我应该从今天早些时候提出另一个问题,因为这个问题与以前有很大不同。我想留下另一个问题作为参考。而且已经很乱了。如果这是一个问题,请告诉我。
据我所知,链接列表中没有添加任何内容。这不会打印任何内容或给我任何错误,这就是我的问题。它应该按字母顺序插入单词。在我看来,一切都是合乎逻辑的。我重做了大部分插入()。
我在每行上用单个单词喂它文件。列表的唯一功能是插入和打印。示例文本(不包括空行):
这是代码:
import sys, os, copy, fileinput
class Node:
def __init__(self, word):
self.data = word
self.next = None
def nextNode(self):
if self.next is not None:
return self.next
else:
return None
def getData(self):
return self.data
def setNext(self, node):
self.next = node
def hasNext(self):
if self.next == None:
return False
else:
return True
class Linked_List:
def __init__(self):
self.head = Node(None)
self.isempty = True
def insert(self, word):
newNode = Node(word)
#Look for position to insert:
#When empty
if self.isempty == True:
self.isempty = False
self.head = newNode
#When has more than two nodes
else:
prev = None
current = self.head
nextFound = False #the next would be the current when it is less than node
while nextFound == False and current != None:
if current.getData() < newNode.getData():
prev = copy.copy(current)
current = current.nextNode()
else:
nextFound = True
if prev == None:
nextNode = copy.copy(current)
self.head = newNode
self.head.setNext(nextNode)
else:
prev.setNext(newNode)
newNode.setNext(current)
def printLinkedList(self):
if self.head.getData() == None:
print("The file was empty.")
else:
prints = self.head
while prints.hasNext():
sys.stdout.write(prints.getData() + '\n')
prints.setNext(prints.nextNode())
linkedlist = Linked_List()
wordlist = ["hello", "jupiter", "albacore", "shrimp", "axe"]
for line in wordlist:
linkedlist.insert(line)
linkedlist.printLinkedList()