Question

In: Computer Science

Insert: this method takes a value as a parameter and adds a node which contains the...

  • Insert: this method takes a value as a parameter and adds a node which contains the value to the end of the linked list

  • Delete: This method deletes a node from the linked list. If an index is passed as a parameter, then the method should delete the node at this index. If no index is passed, then delete the first item in the list

  • Find: this method takes a value as a parameter, and returns the index of the first node which contains this value. If no nodes are found to contain this value, return False

  • Reverse: this method reverses the Linked List

  • Do not edit Lab5.py except to complete the methods required, and to add your name and student number at the top of the file. Any adjustments to the file outside of these will result in grades being deducted.

    You do not need to concern yourself with error handling. For example, you can assume that when delete is called, it is called with an appropriate index.

class Node:

    def __init__(self, dataval=None):

        self.dataval = dataval

        self.nextval = None

class LinkedList:

    def __init__(self):

        self.headval = None

    def __str__(self):

        node = self.headval

        output = "[ "

        while(node != None):

            output = output + str(node.dataval) + ", "

            node = node.nextval

        if(len(output) > 2):

            output = output[:-2]

        return output + " ]"

# DO NOT EDIT ANY CODE ABOVE THIS LINE

    def insert(self, val):

        # Fill in this method, which takes a value and adds a node which holds the value at the end of the linked list

    def delete(self, index=0):

        # Fill in this method, which takes an index(with a default value of 0), and deletes the node at the index specified

    def find(self, val):

        # Fill in this method, which takes in a value and returns the index of the first node which contains that value. If no node containing that value is found, return False

    def reverse(self):

        # Fill in this method, which reverses the list

#DO NOT EDIT ANY CODE PAST THIS LINE

# Tests

# Insertion

a = LinkedList()

a.insert(1)

a.insert(2)

a.insert('a')

a.insert(3)

print(str(a) == "[ 1, 2, a, 3 ]")

# Deletion

a.delete()

print(str(a) == "[ 2, a, 3 ]")

a.delete(2)

print(str(a) == "[ 2, a ]")

# Find

a.insert('b')

a.insert('c')

a.insert('b')

print(a.find('b') == 2)

print(a.find('c') == 3)

print(a.find('d') == False)

# Reverse

a.reverse()

print(str(a) == "[ b, c, b, a, 2 ]")

Solutions

Expert Solution

Program

Text format:

class Node:
    def __init__(self, dataval=None):
        self.dataval = dataval
        self.nextval = None


class LinkedList:
    def __init__(self):
        self.headval = None

    def __str__(self):
        node = self.headval
        output = "[ "
        while (node != None):
            output = output + str(node.dataval) + ", "
            node = node.nextval
        if (len(output) > 2):
            output = output[:-2]
        return output + " ]"

    # DO NOT EDIT ANY CODE ABOVE THIS LINE

    def insert(self, val):
        # Fill in this method, which takes a value and adds a node which holds the value at the end of the linked list
        new_node = Node(val)
        if self.headval is None:
            self.headval = new_node
        else:
            cur = self.headval
            while cur.nextval is not None:
                cur = cur.nextval
            cur.nextval = new_node

    def delete(self, index=0):
        # Fill in this method, which takes an index(with a default value of 0), and deletes the node at the index specified
        if index == 0:
            self.headval = self.headval.nextval
        else:
            cur = self.headval
            pre = None
            for i in range(index):
                pre = cur
                cur = cur.nextval
            pre.nextval = cur.nextval

    def find(self, val):
        # Fill in this method, which takes in a value and returns the index of the first node which contains that value. If no node containing that value is found, return False
        cur = self.headval
        index = 0
        while cur!= None and cur.dataval != val:
            cur = cur.nextval
            index += 1
        if cur != None:
            return index
        return False

    def reverse(self):
        # Fill in this method, which reverses the list
        prev = None
        cur = self.headval
        while cur is not None:
            next = cur.nextval
            cur.nextval = prev
            prev = cur
            cur = next
        self.headval = prev


# DO NOT EDIT ANY CODE PAST THIS LINE

# Tests

# Insertion
a = LinkedList()
a.insert(1)
a.insert(2)
a.insert('a')
a.insert(3)
print(str(a) == "[ 1, 2, a, 3 ]")

# Deletion
a.delete()
print(str(a) == "[ 2, a, 3 ]")
a.delete(2)
print(str(a) == "[ 2, a ]")

# Find
a.insert('b')
a.insert('c')
a.insert('b')
print(a.find('b') == 2)
print(a.find('c') == 3)
print(a.find('d') == False)

# Reverse
a.reverse()
print(str(a) == "[ b, c, b, a, 2 ]")


Output:

True
True
True
True
True
True
True

Solving your question and helping you to well understand it is my focus. So if you face any difficulties regarding this please let me know through the comments. I will try my best to assist you.
Thank you.


Related Solutions

Python linked lists ● Insert: this method takes a value as a parameter, and adds a...
Python linked lists ● Insert: this method takes a value as a parameter, and adds a node which contains the value to the end of the linked list ● Delete: this method deletes a node from the linked list. If an index is passed as a parameter, then the method should delete the node at this index. If no index is passed, then delete the first item in the list ● Find: this method takes a value as a parameter,...
In java please create a method that will insert a value after a specific node for...
In java please create a method that will insert a value after a specific node for a linked list. public void insertAfter(Node a, int newData){ }
Write a static method called "evaluate" that takes a string as a parameter
In Java language  Write a static method called "evaluate" that takes a string as a parameter. The string will contain a postfix expression, consisting only of integer operands and the arithmetic operators +, -, *, and / (representing addition, subtraction, multiplication, and division respectively). All operations should be performed as integer operations. You may assume that the input string contains a properly-formed postfix expression. The method should return the integer that the expression evaluates to. The method MUST use a stack...
In an application write a method filterStack that takes a stack of integers as a parameter...
In an application write a method filterStack that takes a stack of integers as a parameter and filters its elements (in a new Stack) in a way that places the even elements at the bottom and the odd ones at the top. The original stack should remain unchanged. You should use a queue (only one queue) as a temporary storage. Use stack and queue operations only to solve this problem. No need to write the main method. For example, if...
Java 1.Write a method removeEvenLength that takes an ArrayList of Strings as a parameter and that...
Java 1.Write a method removeEvenLength that takes an ArrayList of Strings as a parameter and that removes all of the strings of even length from the list. 2. Given the following Vehicle interface and client program in the Car class: public interface Vehicle{ public void move(); } public class Car implements Vehicle{ public static void main(String args[]) Vehicle v = new Vehicle(); // vehicle declaration } The above declaration is valid? True or False? 3. Java permits a class to...
Write a method that takes an integer array as its parameter and sorts the contents of...
Write a method that takes an integer array as its parameter and sorts the contents of the array in ascending order using the Insertion Sort algorithm. Call this method after the original array and other stats have been displayed. Once the array has been sorted by your method, display its contents to the screen in the same manner as the original array was displayed. CODE SO FAR: import java.util.*; public class ArrayInteger { public static void getRandomNumber(int A[],int n){ Random...
Define a function called 'filterWords, which takes a parameter. The first parameter, text" is an nltk.text.Text...
Define a function called 'filterWords, which takes a parameter. The first parameter, text" is an nltk.text.Text object. The function definition code stub is given in the editor. Perform the given operation for the 'text' object and print the results: • Filter the words whose length is greater than 15 from the complete set of 'text', and store into "large_words' variable as a list
.. Write a method called findNums that takes a two-dimension array of integers as a parameter...
.. Write a method called findNums that takes a two-dimension array of integers as a parameter and returns the number of times a two-digit number appears in the array. For example, if the array (as created by the program below) is 10 45 3 8 2 42 3 21 44 The value returned would be 5 (there are 5 two-digit numbers in the array) public class Question2 {    public static void main(String args[]){      int arr[][] = {{10, 45,...
Write a method that takes four strings as parameter. The first string should be a pokemon...
Write a method that takes four strings as parameter. The first string should be a pokemon name, the second a pokemon type, the third a pokemon name, and the fourth a pokemon type. The method should print out which pokemon has the advantage over the other based on their type. In this case you can use fire, water, and leaf. Example outputs should be like: Example: Pokemon X (Water) has the advantage over Pokemon Y (fire) Pokemon X (Fire) has...
Please use JAVA to do this: Write a method that takes four strings as parameter. The...
Please use JAVA to do this: Write a method that takes four strings as parameter. The first string should be a pokemon name, the second a pokemon type(either fire, water, or leaf, where water beats fire, fire beats leaf and leaf beats water), the third a pokemon name, and the fourth a pokemon type. The method should print out which pokemon has the advantage over the other based on their type. Example: Pokemon X(which is the fire type) has the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT