简体   繁体   English

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

[英]How to delete a node in a linked list in python?

So far I've come up with the code to create a linked list from a normal 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

Using this code I am able to turn a normal list such as [1,2,3,4] into this instead by running createList(plist): 使用此代码,我可以通过运行createList(plist)来将诸如[1,2,3,4]之类的普通列表转换为:

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

Right now what I'm trying to do is delete any node that is the same as another node in the linked list. 现在,我正在尝试删除与链表中另一个节点相同的任何节点。 So if I were to run the program with a list such as [1,1,2,5,7,7,8,8,10,10,10,10,10] it would return 1,2,5,7,8,10. 因此,如果我使用列表[1,1,2,5,7,7,8,8,10,10,10,10,10,10]来运行程序,它将返回1,2,5,7 ,8,10。 I was wondering how I would go about deleting duplicate nodes from the dictionary (linked list) I am creating. 我想知道如何从正在创建的字典(链接列表)中删除重复的节点。 So far this is the code I've come up with but I don't really know where to go from here: 到目前为止,这是我想出的代码,但是我真的不知道从这里可以得到什么:

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

And to test this is the function I am using: 为了测试这是我正在使用的功能:

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

Any help is greatly appreciated! 任何帮助是极大的赞赏! :) :)

Just make a set out of the list, convert back to a list, and all duplicates will be eliminated. 只需从列表中取出一组,然后转换回列表即可,所有重复项都将被消除。

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

This will eliminate duplicates from plist before the for index in range iteration and plist will only retain unique values. 这将在范围迭代中的for索引之前消除plist中的重复项,并且plist将仅保留唯一值。 Is this what you're looking for or are you trying to eliminate only consecutive duplicate values? 这是您要查找的内容吗?还是想消除仅连续的重复值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM