Question

Python 3: Write a LinkedList method named contains, that takes a value as a parameter and...

Python 3:

Write a LinkedList method named contains, that takes a value as a parameter and returns True if that value is in the linked list, but returns False otherwise.

class Node:
    """
    Represents a node in a linked list
    """
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    """
    A linked list implementation of the List ADT
    """
    def __init__(self):
        self.head = None

    def add(self, val):
        """
        Adds a node containing val to the linked list
        """
        if self.head is None:  # If the list is empty
            self.head = Node(val)
        else:
            current = self.head
            while current.next is not None:
                current = current.next
            current.next = Node(val)

    def display(self):
        """
        Prints out the values in the linked list
        """
        current = self.head
        while current is not None:
            print(current.data, end=" ")
            current = current.next
        print()

    def remove(self, val):
        """
        Removes the node containing val from the linked list
        """
        if self.head is None:  # If the list is empty
            return

        if self.head.data == val:  # If the node to remove is the head
            self.head = self.head.next
        else:
            current = self.head
            while current is not None and current.data != val:
                previous = current
                current = current.next
            if current is not None:  # If we found the value in the list
                previous.next = current.next

    def is_empty(self):
        """
        Returns True if the linked list is empty,
        returns False otherwise
        """
        return self.head is None
0 0
Add a comment Improve this question Transcribed image text
Answer #1

THE METHOD CONTAINS IS BELOW WHICH WILL TAKE A ARGUMENT AND WILL RETURN TRUE IF THAT ELEMENT IS PRESENT IN THE LINK LIST AND FALSE IF NOT PRESENT.

def contains(self, item):  # contains method
    current = self.head   # here I have taken the head of the linklist and saved it to current 
    while current is not None:  # and iterated till the head is not empty
        if current.data == item:  # checking if the present node data is equal to the parameter
            return True   # if found returning true
        current = current.next  # else changing the node to the next node
    return False  # if after iterating the whole linklist, the element is not matched then returning false

THE WHOLE CODE WITH CONTAINS IS BELOW WITH OUTPUT:-

THE OUTPUT IS BELOW:-

THANK YOU

Add a comment
Know the answer?
Add Answer to:
Python 3: Write a LinkedList method named contains, that takes a value as a parameter and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display,...

    Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display, remove methods. You may use default arguments and/or helper functions. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list """ if self.head is...

  • Python question. i have to start from an empty linked list, using the method addNodeEnd() to...

    Python question. i have to start from an empty linked list, using the method addNodeEnd() to add the nodes containing the values (3*i+5)%17, where i is from 0 to 10. Then print the values of all the nodes in this linked list to the screen. This is the code that i created right here and i need help checking if i made any mistakes thanks! The code is below: class Node: def __init__(self, data): self.data = data self.next = None...

  • PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None   

    PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None        self.__size = 0    # Return the head element in the list    def getFirst(self):        if self.__size == 0:            return None        else:            return self.__head.element        # Return the last element in the list    def getLast(self):        if self.__size == 0:            return None        else:            return self.__tail.element    # Add an element to the beginning of the list    def addFirst(self, e):        newNode = Node(e) # Create a new node        newNode.next = self.__head # link...

  • Write an implementation similar to the Priority Queue method (from chapter 26) to the linked list...

    Write an implementation similar to the Priority Queue method (from chapter 26) to the linked list using node. (from chapter 24). Your code should utilize the selectionsort method from attached and create another method call selectionsort in linkedlist class. To demonstrate the usage of the selection sort method, you should manually create a link list of random integer (say of 5 numbers), and you need to demonstrate the use the selection sort to sorted the link list. Please submit your...

  • PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree,...

    PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree, the BinaryTreeclass, he wrote test code and is having problems understanding the error. Locate his problem and explain how you would fix it. class Node(object): def __init__(self, data=None): self.data = data def __str__(self): return "NODE: " + str(self.data)    class Tree(object): def __init__(self): self.root_node = None self.size = 0    def __len__(self): return self.size    def add(self, data): raise NotImplementedError("Add method not implemented.")    def inorder_traversal(self): raise NotImplementedError("inorder_traversal...

  • """ Add_to_front(self, val) and add_to_back(self, val) functions can be used which are already done in python...

    """ Add_to_front(self, val) and add_to_back(self, val) functions can be used which are already done in python class. Name of list is LList class node(object): def __init__(self, data, next=None): self.data = data self.next = next # Note: use the attributes directly; no setters or getters! class LList(object): def __init__(self): self._size = 0 self._head = None self._tail = None """ def set_data_at_index(self, idx, val): """ The value stored at index idx changes to val return True if the index was valid otherwise...

  • Finish each function python 3 LList.py class node(object): """ A version of the Node class with...

    Finish each function python 3 LList.py class node(object): """ A version of the Node class with public attributes. This makes the use of node objects a bit more convenient for implementing LList class.    Since there are no setters and getters, we use the attributes directly.    This is safe because the node class is defined in this module. No one else will use this version of the class. ''' def __init__(self, data, next=None): """ Create a new node for...

  • Python question class LinkNode: def __init__(self,value,nxt=None): assert isinstance(nxt, LinkNode) or nxt is None self.value = value...

    Python question class LinkNode: def __init__(self,value,nxt=None): assert isinstance(nxt, LinkNode) or nxt is None self.value = value self.next = nxt Question 2.1. Empty Node In some cases in it convenient to have a notion of an empty linked list. Usually it means that the linked list does not have any elements in it. In order to keep things simple (for now) we will assume that the list is empty, if it has a single node and its value is None. Add...

  • class Node(object): def __init__(self, data, next=None): self.data = data self.next = next class List(object):    def...

    class Node(object): def __init__(self, data, next=None): self.data = data self.next = next class List(object):    def __init__(self): self.head = None self.tail = None Implement the following functions for Linked List in Python and use the constructors above : Copy(lList) Builds and returns a copy of list ItemAt(List,i) Returns the data item at position i in list Pop(List,i=0) Remove item at position i in list. If i is not specified, it removes the first item in list Count(List,x) Returns the number...

  • Python code that sorts books

    class Book:    def __init__(self,id,bookName,authorName,nextNode=None):         self.id = id         self.bookName = bookName         self.authorName = authorName         self.nextNode = nextNode    def getId(self):        return self.id     def getBookName(self):        return self.bookName    def getAuthorName(self):        return self.authorName    def getNextNode(self):        return self.nextNode       def setNextNode(self,val):         self.nextNode = val   class LinkedList:    def __init__(self,head = None):         self.head = head         self.size = 0     def getSize(self):        return self.size    def AddBookToFront(self,newBook):         newBook.setNextNode(self.head)         self.head = newBook         self.size+=1     def DisplayBook(self):         curr = self.head        while curr:            print(curr.getId(),curr.getBookName(),curr.getAuthorName())              curr = curr.getNextNode()    def RemoveBookAtPosition(self,n):         prev = None         curr = self.head         curPos = 0         while curr:            if curPos == n:                if prev:                     prev.setNextNode(curr.getNextNode())                else:                     self.head = curr.getNextNode()                 self.size = self.size - 1                 return True                  prev = curr             curr = curr.getNextNode()              curPos = curPos + 1          return False     def AddBookAtPosition(self,newBook,n):         curPos = 1         if n == 0:             newBook.setNextNode(self.head)             self.head = newBook             self.size+=1             return         else:             currentNode = self.head            while currentNode.getNextNode() is not None:                if curPos == n:                     newBook.setNextNode(currentNode.getNextNode())                     currentNode.setNextNode(newBook)                     self.size+=1                     return                 currentNode = currentNode.getNextNode()                 curPos = curPos + 1             if curPos == n:                 newBook.setNextNode(None)                 currentNode.setNextNode(newBook)                 self.size+=1             else:                print("cannot add",newBook.getId(),newBook.getBookName(),"at that position")    def SortByAuthorName(self):        for i in range(1,self.size):             node1 = self.head             node2 = node1.getNextNode()            while node2 is not None:                if node1.authorName > node2.authorName:                     temp = node1.id                     temp2 = node1.bookName                     temp3 = node1.authorName                     node1.id = node2.id                     node1.bookName = node2.bookName                     node1.authorName = node2.authorName                     node2.id = temp                     node2.bookName = temp2                     node2.authorName = temp3                 node1 = node1.getNextNode()                 node2 = node2.getNextNode()     myLinkedList = LinkedList() nodeA = Book("#1","cool","Isaac") nodeB = Book("#2","amazing","Alfred") nodeC = Book("#3","hello","John") nodeD = Book("#4","why","Chase") nodeE = Book("#5","good","Mary") nodeF = Book("#6","hahaha","Radin") myLinkedList.AddBookToFront(nodeA) myLinkedList.AddBookToFront(nodeB) myLinkedList.AddBookToFront(nodeC) myLinkedList.AddBookAtPosition(nodeD,1) myLinkedList.AddBookAtPosition(nodeE,1) myLinkedList.AddBookAtPosition(nodeF,1) myLinkedList.RemoveBookAtPosition(2) myLinkedList.RemoveBookAtPosition(2) myLinkedList.DisplayBook() myLinkedList.SortByAuthorName()print(myLinkedList.getSize())...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT