Python - 链接列表插入节点

时间:2014-04-03 23:18:37

标签: python list linked-list

基本上我正在尝试创建一个函数来将节点添加到现有链表(不使用类)。 当我调用一个测试器函数时,我得到了一堆奇怪的输出(即"无"它出现在它应该没有的地方),我无法找到它。任何人都可以伸出援手吗?

# 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!
'''

1 个答案:

答案 0 :(得分:-1)

else函数内的insertNode分支中,您只需return,这意味着Python中的return None。在这种情况下,您可能也希望return linkedList