Question

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
  
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
# Add a end instance variable for the linked list
# So that we can know the end of the linked list.
self.end = self.head

# find a node which contains the data matching the input value
def findNode(self, value):
curr = self.head
while curr:
if curr.data == value:
return curr
curr = curr.next
return curr

# add a new node as the first node
def addNode(self, data):
newNode = Node(data) # create the new node
newNode.next = self.head
self.head = newNode
self.size+=1
# We have to set the head's next to the newNode Node.
self.head.setNext(newNode)
# We have to set the head's next to the newNode Node.
self.end = newNode

# Append at the last
def addNodeEnd(self,data):
# create a node
appendKey=Node(data)
# append it to the tail of the SinglyLinkedList
self.end.next=appendKey
# make this appendKey node as the new tail
self.end=appendKey

# print the data in all the nodes
def printNode(self):
curr = self.head
while curr:
print(curr.data)
curr = curr.next

#driving code that creates the list
myList = LinkedList()

for i in range(10):
myList.addNodeEnd((3*i+5)%17)

#prints the results
myList.printNode()   

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Screenshot

C. C:\WINDOWS\system32\cmd.exe class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: defself.head.next=self.end else: newNode.next = self.head self.head = newNode self.size+=1 # Append at the last def addNodeEnd(scurr = self.head while curr!=self.end: print(curr.data) curr = curr.next #driving code that creates the list myList = LinkedL

Program

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

class LinkedList:
    def __init__(self):
        self.head = None
        self.size = 0
        # Add a end instance variable for the linked list
        # # So that we can know the end of the linked list.
        self.end = self.head
   # find a node which contains the data matching the input value
    def findNode(self, value):
       curr = self.head
       while curr:
           if curr.data == value:
               return curr
           curr = curr.next
       return curr
     # add a new node as the first node
    def addNode(self, data):
         newNode = Node(data) # create the new node
         if(self.head==None):
             self.head=newNode
             self.head.next=self.end
         else:
            newNode.next = self.head
            self.head = newNode
            self.size+=1
       
    # Append at the last
    def addNodeEnd(self,data):
        # create a node
        appendKey=Node(data)
        if self.head==None:
            self.head=appendKey
            self.head.next=self.end
            self.size+=1
        else:
            curr=self.head
            while(curr.next!=self.end):
                curr=curr.next
            curr.next=appendKey
            curr.next.next=self.end
            self.size+=1
          

    # print the data in all the nodes
    def printNode(self):
        curr = self.head
        while curr!=self.end:
            print(curr.data)
            curr = curr.next

#driving code that creates the list
myList = LinkedList()
for i in range(10):
    myList.addNodeEnd((3*i+5)%17)

#prints the results
myList.printNode()

Output

5
8
11
14
0
3
6
9
12
15

Add a comment
Know the answer?
Add Answer to:
Python question. i have to start from an empty linked list, using the method addNodeEnd() to...
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
  • from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked...

    from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked list. Note that this is considered a "private class", one which is only meant to be used in this module by the LinkedList class, but not by client code. === Attributes === item: The data stored in this node. next: The next node in the list, or None if there are no more nodes. """ item: Any next: Optional[_Node] def __init__(self, item: Any) ->...

  • 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 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...

  • 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 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())...

  • Given a singly linked list contains 5 nodes, which simply shows as 5->4->3->2->1, what is the...

    Given a singly linked list contains 5 nodes, which simply shows as 5->4->3->2->1, what is the value that you can find in the second node of the remaining list if the following statements are applied? Assume head reference refers the first node of the list. Node prev = head; Node curr = head. next; while(curr.next!=null) { if(prev.element > 3) { prev = curr; curr = curr.next; } else break; } head = prev.next; Question 3 options: 3 2 4 1...

  • What is the specific answer for 1. and 2. Thanks! Add a new method, find, to...

    What is the specific answer for 1. and 2. Thanks! Add a new method, find, to class SinglyLinkedList (defined here) that takes as input a “data” value and returns a pointer to a node. If the input data is present in the linked list, the returned pointer should point to that node; if not, the returned pointer is nullptr. Write the (single line) method declaration/specification. Write the method definition/implementation. Test by running the main() function below and capture the console...

  • Question 2 (3 points) Given the following singly linked list (a list with four nodes), what...

    Question 2 (3 points) Given the following singly linked list (a list with four nodes), what will be the value stored at the last node when the following operations are executed? head->1111-151->11011->1211 Node curr = head; while(curr next !=null) { curr.item = curritem-head. item; curr = cur next; اسرة Node newNode = new Node(8): curr.next = newNode: 23 O 12 OS O21 Question 3 (3 points) Given a recursive method as shown below, what is the return value for P(5)...

  • 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...

  • 1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing...

    1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing the nodes added to the min spanning tree and the order they are added. Using Python. Starter code: from collections import deque class Edge: def __init__(self, endIndex, next = None): self.endIndex = endIndex self.next = next class Node: def __init__(self, name): self.name = name self.visited = False self.connects = None class Graph: def __init__(self): self.nodeList = [] self.size = 20...

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