简体   繁体   English

Python-链表插入节点

[英]Python - Linked Lists Inserting Nodes

Basically I am trying to make a function to add a node to an existing linked list (without using a Class). 基本上,我试图使函数将节点添加到现有的链表中(不使用Class)。 When I call a tester function, I get a bunch of strange outputs (namely "None" comes up where it shouldn't), and I am having trouble locating this. 当我调用测试器函数时,会得到一堆奇怪的输出(即在不应该出现的地方出现“ None”),并且在查找该输出时遇到了麻烦。 Can anyone give a hand? 谁能帮忙?

# Function to insert new node in any valid index
def insertNode(List, index, value):

linkedList = List
newnode = {}
newnode['data'] = value
if index < 0 or index > len(List):
    print "Index not found!"
    return List
if index == 0:
    newnode['next'] = linkedList
    linkedList = newnode
    return linkedList
else:
    before = nthNode(linkedList, index - 1)
    before = nthNode(linkedList, index)
    after = nthNode(linkedList, index + 1)
    before['next'] = newnode['data']
    newnode['next'] = after['data']
return


def ListString(linkedList):
#creates a string representation of the values in the linked List
ptr = linkedList
str1 = "["
while ptr != None:
str1 += str(ptr['data'])
ptr = ptr['next']
if ptr != None:
str1 += ","
str1 = str1 + "]"
return str1

def printList(linkedList):
#prints all the values in the linked List
print "in printList"
print ListString(linkedList)

def testInsert():
#test code to ensure that insertNode is working correctly.
myList = createList([1, 2, 3, 4, 5, 6])
print "The initial list", printList(myList)
#insert 0 at the head
myList = insertNode(myList,0, 0)
print "Inserted 0 at the start of list: ", printList(myList)
#insert 7 at the end
myList = insertNode(myList, 7, 7)
print "Inserted 7 at the end of list: ", printList(myList)
myList= insertNode(myList, 3, 2.2)
print "Inserted 2.2 in the 3rd position ", printList(myList)
myList = insertNode(myList, 26, 12)

# tester function to check all aspects of insertNode is working

# The following is the output from calling testInsert():
'''
The initial List in printList
[1,2,3,4,5,6]
None
Inserted 0 at the start of List:  in printList
[0,1,2,3,4,5,6]
None
Index not found!
Inserted 7 at the end of List:  in printList
[0,1,2,3,4,5,6]
None
Index not found!
Inserted 2.2 in the 3rd position  in printList
[0,1,2,3,4,5,6]
None
Index not found!
'''

In the else branch inside the insertNode function you just return , which means return None in Python. insertNode函数内部的else分支中,您只需return ,这意味着在Python中return None You probably want to return linkedList in this case as well. 在这种情况下,您可能还想return linkedList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM