我想创建一个将节点插入链表中任何位置的函数。 有一个测试功能来测试该功能是否有效。我的问题是,当我运行测试功能时,没有任何输出显示,任何想法?
"""
Creates and returns a linked list containing all of the elements
of the Python-style list parameter.
"""
def createList(plist):
myList = None
# goes backwards, adding each element to the beginning
# of the list.
for index in range(len(plist)-1, -1, -1):
myList = insertValueHead(myList, plist[index])
return myList
'''
Creates a string representation of the values in the linked list such as:
5->6->9->14.
'''
def listString(myList):
ptr = myList
str1 = ''
while ptr != None:
str1 += str(ptr['data'])
ptr = ptr['next']
if ptr != None:
str1 += "->"
str1 = str1
return str1
'''
Inserts a new node containing the value "value" to the head of the list.
LinkedList is the head of the list to be added to
Value is the data to be stored in the node'''
def insertValueHead(myList, value):
newnode = {}
newnode["data"] = value
#set the next pointer of this new node to the head of the list, linkedList
#newnode is now the head of the list
newnode["next"] = myList
return newnode
def insertNode(myList, index, value):
if index == 0:
newnode = {}
newnode["data"] = value
newnode["next"] = myList
elif index > 0:
newnode = {}
newnode["data"] = value
ptr = myList
count = 0
while ptr != None and count < index-1:
ptr = ptr['next']
print count
count += 1
return ptr
newnode['next'] = ptr['next']
ptr['next'] = newnode
def testInsert():
#test code to ensure that insertNode is working correctly.
myList = createList([1, 2, 3, 4, 5, 6])
print "The initial list", listString(myList)
#insert 0 at the head
myList = insertNode(myList,0, 0)
print "Inserted 0 at the start of list: ", listString(myList)
#insert 7 at the end
myList = insertNode(myList, 7, 7)
print "Inserted 7 at the end of list: ", listString(myList)
myList= insertNode(myList, 3, 2.2)
print "Inserted 2.2 in the 3rd position: ", listString(myList)
myList = insertNode(myList, 26, 12) #should generate an error
testInsert()
答案 0 :(得分:3)
在索引0处插入时,insertNode()
函数永远不会返回newnode
。因此,会返回None
。
由于这是构建初始链表后testInsert()
函数执行的第一个操作,因此该函数中的myList
现在为None
,其余测试无效。
对于index > 0
案例,您的return
声明来得太早;您返回ptr
,例如插入新值之前index - 1
处的节点。 <{1}}语句之后的所有语句都不会被执行。
你真的不需要return
案例的特殊情况。这是一个更好的版本:
index = 0
如果您尝试在结束时插入值,则此版本实际上会引发错误;在这种情况下,def insertNode(myList, index, value):
newnode = {'data': value, 'next': None}
retval = myList if index else newnode
prev, ptr = None, myList
while ptr is not None and index > 0:
prev, ptr = ptr, ptr['next']
index -= 1
if index > 0:
raise ValueError('Index out of range')
newnode['next'] = ptr
if prev is not None:
prev['next'] = newnode
return retval
将大于0。
答案 1 :(得分:1)
此代码无法访问:
return ptr
newnode['next'] = ptr['next'] # unreachable after a returnn statement
ptr['next'] = newnode
尝试在while循环中移动代码并返回之前:
elif index > 0:
newnode = {}
newnode["data"] = value
ptr = myList
count = 0
while ptr != None and count < index-1:
ptr = ptr['next']
print count
count += 1
newnode['next'] = ptr['next']
ptr['next'] = newnode
return ptr