简体   繁体   中英

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):

{'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. 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. Is this what you're looking for or are you trying to eliminate only consecutive duplicate values?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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