我在为部分代码设置索引时遇到了一些麻烦。关键功能是switch()其他一切都很好。 switch函数的作用是获取给定索引处的节点,并将其与列表头部的节点进行切换。我是如此接近,但我无法弄清楚为什么当我运行测试功能(testswitch())的第一种情况下它不会输出前两个节点,然后因为列表已被更改,第二个测试用例赢了' t由于TypeError而运行。任何帮助表示赞赏
"""
Creates and returns a linked list containing all of the elements
of the Python-style list parameter.
"""
def createList(plist):
myList = None
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(linkedList):
ptr = linkedList
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 nthNode(myList, index):
ptr = myList
count = 0
if index < 0:
return None
while ptr != None and count < index:
ptr = ptr['next']
count += 1
return ptr
def switch(myList, index):
newnode = {}
newnode['data'] = 0
newnode['next'] = None
temphead = myList
head = myList
head = head['next']
if index != 0:
output = myList
else:
output = newnode
prev, ptr = None, myList
while ptr != None and index >0:
prev = ptr
ptr = ptr['next']
index = index - 1
if index > 0:
print ('Index out of range')
temphead['next'] = ptr['next']
ptr['next'] = head
prev['next'] = temphead
print ptr['data']
return output
def testSwitch():
#test code to ensure that switch() is working correctly.
myList = createList([10, 20, 30, 40, 50, 60])
print "The initial list", listString(myList)
myList = switch(myList, 2)
print "Switching the head and the 30. Resulting list is ", listString(myList)
myList = switch(myList, 5)
print "Switching the head and the 60. Resuling list is ", listString(myList)
myList = switch(myList, 29) #should result in an error
testSwitch()
这是追溯
Traceback (most recent call last):
File "C:/Users/Hassan/Desktop/Python/assignment4.py", line 122, in <module>
testSwitch()
File "C:/Users/Hassan/Desktop/Python/assignment4.py", line 119, in testSwitch
myList = switch(myList, 5)
File "C:/Users/Hassan/Desktop/Python/assignment4.py", line 105, in switch
temphead['next'] = ptr['next']
TypeError: 'NoneType' object has no attribute '__getitem__'