問題が以前とは大きく異なっているため、今日は以前から別の質問をする必要があると感じました。そして、他の質問を参考にしたいと思いました。また、それはすでにかなり雑然としていました。これが問題である場合は、お知らせください。
私が知る限り、リンクされたリストには何も追加されていません。これは何も出力せず、エラーも発生しません。それが私の問題です。単語をアルファベット順に挿入することになっています。私にはすべてが論理的に思えます。insert() のほとんどをやり直しました。
各行に単一の単語を含むファイルをフィードします。リストの唯一の機能は挿入と印刷です。テキストの例 (空白行を含まない):
コードは次のとおりです。
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()