Python - 链表节点插入
基本上,我想写一个函数,把一个节点添加到已经存在的链表里(不使用类)。但是当我调用一个测试函数时,输出了一堆奇怪的结果(比如出现了“None”,而这个地方不应该有这个),我现在很难找到问题出在哪里。有没有人能帮帮我?
# 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 个回答
-1
在 insertNode
函数的 else
分支里,你只是用了 return
,这在 Python 里意味着 return None
。你可能想在这种情况下也返回 linkedList
。