2014-04-03 3 views
0

기본적으로 클래스를 사용하지 않고 기존의 링크 된 목록에 노드를 추가하는 함수를 만들려고합니다. 테스터 기능을 호출하면 이상한 결과가 나옵니다 (즉, "없음"이 나타나지 않아야합니다).이 위치를 찾는 데 문제가 있습니다. 누구든지 손을 댈 수 있습니까? 파이썬에서 return None을 의미 insertNode 기능 방금 return, 내부 else 지점에서파이썬 링크 된 목록 노드 삽입

# 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'는 파이썬의 키워드입니다 – shaktimaan

+2

어떤 부분이 어떤 함수에 있어야하는지 알려면 코드의 형식을 올바르게 지정하십시오. –

+0

우리의 교수는이 해골 코드를 많이 제공했는데, 키워드로 변수를 사용했지만 아무것도 남겨 두지 않았 음을 확인했습니다. 나는 대문자로 표기 했으므로 이제는 그 문제가 해결되었습니다. 나는 포맷팅 측면에서도 더 명확하게하려고 노력했다. 고맙습니다. – user3072912

답변

-1

. 이 경우에는 return linkedList을 원할 수도 있습니다.