使用列表头部在索引处交换节点?

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

标签: python linked-list

我目前正在尝试创建一个函数,该函数将使用列表头部切换索引处的节点。因此,如果我的列表(列表)具有值[1,7,9,12]并且我调用switch(list,2),则我的结果将是[9,7,1,12]。这是我到目前为止的代码:

"""
Creates and returns a linked list containing all of the elements
of the Python-style list parameter.  A useful shortcut for testing.
"""
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

'''
Create an empty linked list
'''
def emptyList():
  return None   #absence of a value -- nothing

'''
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(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

"""
Helper method: returns a reference to node n in a list counting from zero).
Parameters: the list and an index n
If there is no node n, returns None.
"""
def nthNode(linkedList, n):
    ptr = linkedList
    count = 0
    if n < 0:
        return None
    while ptr != None and count < n:
        ptr = ptr['next']
        count += 1
    return ptr

def switch(j, index):
  head = j
  currentItem = j       # The head again
  prevItem = None       # The item that links to tempItem
  for x in range(index):    # Find the item to swap
    prevItem = currentItem
    currentItem = currentItem['next']

  # Now we swap. We're rotating three items' .next values, so we can't
  # do the really optimized way.
  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)
    myList = switch(myList, 3)
    print "Switching the 4 and the 5.  Resuling list is ", listString(myList)
    myList = switch(myList, 5)  
    myList = switch(myList, 29)  #should result in an error

从switch()函数中我得到一个错误,说出AttributeError:&#39; dict&#39;对象没有属性&#39; next&#39;。我怎样才能解决这个问题呢?我哪里错了?

编辑1:我已将参数列表更改为j并将开关功能.nexts更改为[&#39; next&#39;]。现在,当运行testSwitch()时,它会出现错误&#34; TypeError:&#39; NoneType&#39;对象没有属性&#39; getitem &#39;&#34;。知道这是从哪里来的吗?我已经对代码进行了梳理,在达到测试部分之前我似乎不应该返回None ...

1 个答案:

答案 0 :(得分:0)

我在your previous question中编写的switch()代码假定每个项目都是具有属性的对象。如果您已将其实施为字典,请使用currentItem['next']代替currentItem.next

编辑:不要使用list这个词作为变量;这已经是一个功能的名称。这会导致问题。