1

I am learning how to use linked lists, and would like to add a value, remove a value, and test if a value is in the linked list. I am struggling to work out how test for a value and remove a value.

class Node(object):
   def __init__(self, v, n):
      self.value = v
      self.next = n

class LinkedList(object):
    def __init__(self):
        self.firstLink = None
    def add (self, newElement):
        self.firstLink = Node(newElement, self.firstLink)
    def test(self, testValue):

    def remove(self, testValue):
1
  • What are you struggling with and why? Commented Oct 20, 2017 at 22:36

1 Answer 1

1

To test if a value is in a LinkedList you have to go through the list and check every item

def contains(self, testValue):
    ptr = self.firstLink
    while ptr != None:
        if ptr.value == testValue:
            return True
        ptr = ptr.next
    return False

When using remove() method you usually don't pick an item to be removed. Remove method should only remove the last item added to LinkedList. Last in, First out.

def remove(self):
    if self.firstLink == None():
        return None
    else:
        item = self.firstLink.value
        self.firstLink = self.firstLink.next
        return item

To learn more about Linked Lists or see how can 'remove element' from LinkedList be implemented in python go to this site. It is well explained in there LinkedList

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

2 Comments

Thank you! The site was very useful aswell.
@Greta Glad I could help

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.