如何在python中删除链表中的节点?

时间:2014-10-20 03:33:57

标签: python linked-list

到目前为止,我已经提出了从正常列表创建链接列表的代码:

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

使用此代码,我可以通过运行createList(plist)将[1,2,3,4]等普通列表转换为此代码:

{'data': 1, 'next': {'data': 2, 'next': {'data': 3, 'next': {'data': 4, 'next': None}}}}

现在我要做的是删除与链表中另一个节点相同的任何节点。因此,如果我使用[1,1,2,5,7,7,8,8,10,10,10,10,10]这样的列表运行程序,它将返回1,2,5,7 ,8.10。我想知道如何从我正在创建的字典(链表)中删除重复的节点。到目前为止,这是我提出的代码,但我真的不知道从哪里开始:

def noDups(plist):
    node = plist
    while node['next'] != None:
        if node['data'] == node['next']['data']:
            del node['next']
        return node

要测试这是我正在使用的功能:

def testNoDups():
nums = createList([1,1,2,5,7,7,8,8,10,10,10,10,10])
print noDups(nums)

非常感谢任何帮助! :)

1 个答案:

答案 0 :(得分:2)

只需从列表中创建一个列表,转换回列表,所有重复项都将被删除。

def createList(plist):

    linkedList = None
    # goes backwards, adding each element to the beginning
    # of the list.
    plist = list(set(plist))   
    for index in range(len(plist)-1, -1, -1):
        linkedList = insertValueHead(linkedList, plist[index])
    return linkedList

这将消除范围迭代中for index之前plist的重复,并且plist将仅保留唯一值。这是您正在寻找的,或者您是否只想消除连续的重复值?