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

0 投票
1 回答
1424 浏览
提问于 2025-04-28 11:41

到目前为止,我写了一段代码,可以把一个普通的列表变成一个链表:

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 个回答

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

这样在进行循环之前,plist中的重复值就会被去掉,plist只会保留唯一的值。你是想要这个效果,还是只想去掉连续的重复值呢?

撰写回答