[英]Using single linked lists, how to swap nodes in python?
目前,我一直在尝试根据我的主要功能switch(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
我究竟做错了什么? 我似乎无法弄清楚...
如果您需要支持开关操作,则简单链接列表不是一个非常有用的构造。 在双链表上,如果节点的指针向前和向后,则非常简单,但是在单链表上,您至少需要扫描一次列表。 而且,您的代码是如此混乱,以至于没人能真正调试它。 从而
switch
操作,您非常想拥有双链表。 也许使用linux链表约定,其中末端也是列表节点 就像是
class Node(object):
prev = None
next = None
class List(object):
def __init__(self):
self.head = self
self.tail = self
self.prev = self
self.next = self
self.nil = self
def insert_head(self, node):
node.next = self.head.next
self.head.next.prev = node
node.prev = self.head
self.head.next = node
def __iter__(self):
current = self.head.next
while current != self.nil:
yield current
current = current.next
def __str__(self): # the "list_string" op
items = []
return ' -> '.join(map(str, self))
class TestNode(Node):
def __init__(self, value):
self.value = value
def __repr__(self):
return repr(self.value)
list = List()
list.insert_head(TestNode('a'))
list.insert_head(TestNode('b'))
print(list)
您的缩进不正确,这就是您遇到问题的原因。
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
在函数或循环内缩进四个空格。 您不能将j [0]分配给当前项目,因为这是字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.