目前,我一直在尝试根据我的主功能开关(myList,index)重新排列链表。
def createList(plist):
linkedList = None
# goes backwards, adding each element to the beginning
# of the list.
for index in range(len(plist)-1, -1, -1):
linkedList = insertValueHead(linkedList, plist[index])
return linkedList
def insertValueHead(linkedList, 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"] = linkedList
return newnode
def listString(linkedList):
ptr = linkedList
str1 = ''
while ptr != None:
str1 += str(ptr['data'])
ptr = ptr['next']
if ptr != None:
str1 += "->"
str1 = str1
return str1
def switch(j, i):
head = j
currentItem = j[0] # The head again
prevItem = 1 # The item that links to tempItem
for x in range(i): # Find the item to swap
prevItem = currentItem
currentItem = currentItem['next']
currentItem = currentItem['next']
temp = currentItem['next']
currentItem['next'] = head['next']
head['next'] = prevItem['next']
prevItem['next'] = temp
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 1 and the 2. Resulting list is ", listString(myList)
testSwitch()
这应该会产生一个包含交换元素的列表。但是,当我运行它时,这是输出:
The initial list 10->20->30->40->50->60
Switching the 1 and the 2. Resulting list is
接下来是错误:
currentItem = currentItem['next']
TypeError: list indices must be integers, not str
我究竟做错了什么?我似乎无法弄清楚...