0

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

1
  • I don't understand if you want just solve the "no duplicate elements in my list problem" or ask for a structure that implement insert and remove efficiently Commented Oct 20, 2014 at 6:41

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.