使用单链表,如何在python中交换节点?

时间:2014-08-05 04:19:28

标签: python python-2.7

目前,我一直在尝试根据我的主要功能开关(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

我做错了什么?我似乎无法弄清楚......

2 个答案:

答案 0 :(得分:2)

如果您需要支持切换操作,那么简单链接列表不是一个非常有用的结构。在双向链表上,如果节点具有前向和后向指针,则非常容易,但在单链表上,您需要至少扫描一次列表。此外,您的代码非常混乱,没有人可以真正调试它。因此

  • 使用基于类的列表,而不是具有Node子类的项目,比如说。
  • 对于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)

答案 1 :(得分:-2)

您的缩进不正确,这就是您遇到问题的原因。

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]指定给当前项目,因为它是一个词典。