无法创建python链表

时间:2014-04-29 23:51:51

标签: python linked-list nodes

这是我现在正在使用的代码,我正在尝试完成insertNode(list,index,value)函数(一个将节点插入空列表的常规插入函数[ @head of list / tail / middle])。

insertNode()函数应该使用"索引"参数,用于指示列表中插入新节点的位置,并应返回已修改列表的头部。

我已经在这方面工作了好几天,我不确定它的语法或理解,代码似乎不起作用。请帮忙。

另外,如果我想将nthNode(例如ptr)的返回值用于另一个函数,那么将它作为全局值是否正确?

global ptr

def createList(plist):
    """
    Creates and returns a linked list containing all of the elements
    of the Python-style list parameter.  A useful shortcut for testing.
    """
    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 emptyList():
  #creates an empty linked list
  return None   #absence of a value -- nothing


def insertValueHead(linkedList, value):
    #linkedList is the head of the list to be added to
    #value is the data to be stored in the node
    #inserts a new value at the head of the linked list
    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 nthNode(linkedList, n):
    """
    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.
    """

    ptr = linkedList
    count = 0
    if n < 0:
        return None

    while ptr != None and count < n:
        ptr = ptr['next']
        count += 1
    return ptr


def insertNode(myList,index,value):

  #This function is a general function for inserting values in a linked list.  I have provided a
  #skeleton, it is your job to complete it.

  #case 1:  Adding to the head of the list -- index == 0
  #Create a new node and pass back the new node, which is the new head of the list.

    if index==0:
        value['next']=linkedList
        linkedList=value
        return linkedList



  #case 2:  Adding elsewhere in the list
  #use nthNode() to find the node before the position to insert (this will be at index - 1)
  #if this function returns None, then the index is invalid -- print an error message
  #otherwise, add the node


    else:
        if nthNode(linkedList,n)==None:
            print 'Index is invalid'
        else:
            ptr=nthNode(linkedList,n)
            value['next']=ptr['next']
            ptr['next']=value 
            return linkedList



def switch(list, index):
  #Add your code here.
  pass  #remove this once you add code

def removeEvens(list):
  #Add your code here
  pass #remove this once you add code



def listString(linkedList):
  #creates a string representation of the values in the linked list
  ptr = linkedList
  str1 = "["
  while ptr != None:
    str1 += str(ptr['data'])
    ptr = ptr['next']
    if ptr != None:
      str1 += ","
  str1 = str1 + "]"
  return str1

def printList(linkedList):
  #prints all the values in the linked list
  print "in printList"
  return listString(linkedList)


def testInsert():
  #test code to ensure that insertNode is working correctly.
  myList = createList([1, 2, 3, 4, 5, 6])
  print "The initial list", printList(myList)
  #insert 0 at the head
  myList = insertNode(myList,0, 0)
  print "Inserted 0 at the start of list: ", printList(myList)
  #insert 7 at the end
  myList = insertNode(myList, 7, 7)
  print "Inserted 7 at the end of list: ", printList(myList)
  myList= insertNode(myList, 3, 2.2)
  print "Inserted 2.2 in the 3rd position ", printList(myList)
  myList = insertNode(myList, 26, 12)   #should generate an error

def testSwitch():
    #test code to ensure that switch() is working correctly.
    myList = createList([1, 2, 3, 4, 5, 6])
    print "The initial list", printList(myList)
    myList = switch(myList, 0)
    print "Switching the 1 and the 2.  Resulting list is ", printList(myList)
    myList = switch(myList, 3)
    print "Switching the 4 and the 5.  Resuling list is ", printList(myList)
    myList = switch(myList, 5)  #should result in an error
    myList = switch(myList, 29)  #should result in an error

def testRemoveEvens():
    #test code to ensure that removeEvens() is working correctly.
    myList= createList([1, 7, 4, 15, 16, 22])
    print "The initial list", printList(myList)
    myList = removeEvens(myList)
    print "With evens removed, list is :", printList(myList)
    myList = createList([2, 7, 4, 15, 16, 3])
    print "The initial list", printList(myList)
    myList = removeEvens(myList)
    print "With evens removed, list is :", printList(myList)


def main():
    #create an empty list
    #linkedList is the head of the list
    linkedList = emptyList()
    print "Inserting a new node with value 9"
    linkedList = insertValueHead(linkedList, 9)
    printList(linkedList)
    print "Inserting a new node with value 20"
    linkedList = insertValueHead(linkedList, 20)
    printList(linkedList)

main()

0 个答案:

没有答案