我正在尝试编写代码来操作链表,这是我到目前为止所拥有的:
def main ():
readFile('list1.txt')
head1 = readFile('list1.txt')
profile1 = head1
readFile('list2.txt')
head2 = readFile('list2.txt')
profile2 = head2
choice(profile1, profile2)
def choice(profile1, profile2):
print(" ")
print("Welcome to your Netflix list!")
print(" ")
print("Type 'one' to view profile #1's custom list")
print("Type 'two' to view profile #2's custom list")
print("type 'merge' to merge the two profile lists")
print("Type 'check' to delete duplicate values in your merged list")
print("Type 'add' to add values to your (profile #1's) list")
print("Type 'delete' to delete a value from your (profile #1's) list")
print(" ")
choice = input("Please input your choice: ").lower()
if (choice == 'one'):
display(profile1, profile1, profile2)
elif (choice == 'two'):
display(profile2, profile1, profile2)
elif (choice == 'merge'):
merge(profile1, profile2)
elif(choice == 'check'):
check(profile1, profile2)
elif (choice == 'add'):
add(profile1, profile2)
elif(choice == 'delete'):
delete(profile1)
else:
print("That input was not understood. Try typing that again")
choice(profile1, profile2)
def add(profile1, profile2):
insert = print(input("Type the name you would like to add: "))
addToEnd(profile1, insert)
choice(profile1, profile2)
def merge(profile1, profile2):
head = profile1
ptr = head
while ptr != None:
print(ptr['data'])
ptr = ptr['next']
choice = print(input("Input number before which to insert the list: "))
ptr = head
while ptr['next'] != choice:
ptr = ptr['next']
nodeAfter = ptr['next']
profile2['next'] = nodeAfter
ptr['next']= profile2
head = profile1
ptr = head
while ptr != None:
print(ptr['data'])
ptr = ptr['next']
def display(profile, profile1, profile2):
head = profile
ptr = head
while ptr != None:
print(ptr['data'])
ptr = ptr['next']
choice(profile1, profile2)
def readFile (file):
with open(file, 'r') as ins:
profile = {}
profile['data'] = ins.readline().strip()
profile['next'] = None
head = profile
for line in ins:
addToEnd(head, line)
return profile
def addToEnd (head, value):
newEntry = {}
newEntry['data'] = value.strip()
newEntry['next'] = None
ptr = head
while ptr['next'] != None:
ptr = ptr['next']
ptr['next'] = newEntry
return ptr
main()
显然应该做的事情比我说的要多,但是我无法超越这些。当我尝试使用'add'函数时,它会记住有一个链接,但它只是说'none',所以输入的内容都会丢失。 同样在合并函数中,它没有这样做,我猜测是因为链接/值没有数字,所以它不知道在哪里插入或类似的东西。是否可以为链表中的值/链接赋予一个数字?我将头部传递给其他功能时也会遇到很多错误,因此一旦完成其他功能就可以返回菜单。我真的不知道出了什么问题,我觉得这可能是我缺少的链表的根本原因。
编辑:我意识到在python中使用链表是没有意义的。但这是我的功课,所以不幸的是,这是我必须做的。