2014-04-03 120 views
0

基本上我试图做一个函数来添加一个节点到现有的链表(不使用类)。 当我调用一个测试函数时,会得到一堆奇怪的输出(即“None”出现在它不应该出现的位置),并且我无法定位它。任何人都可以举手吗?Python - 链接列表插入节点

# 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

请不要使用'list'作为变量名称。 'list'是python中的关键字 – shaktimaan

+2

请正确格式化您的代码,以便我们可以确定哪些部分应该在哪些函数中。 –

+0

我们的教授给了我们很多这样的骨架代码,我注意到她使用了一个关键字作为变量,但是保持原样,以确保没有任何变化。我把这个字母大写,所以现在这个问题已经被处理了。 我也尝试使格式更清晰, 非常感谢 – user3072912

回答

-1

insertNode功能您只需return,这意味着在Python return Noneelse分支。在这种情况下,你可能也想要return linkedList