Question

In: Computer Science

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, 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

Python Code:

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

Complete code in python3:-

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
node = self.headval
# If list is empty, simply assign new node to self.headval and return
if node == None:
self.headval = Node(val)
return

# Else traverse whole list and insert new node at the end.
while node.nextval != None:
node = node.nextval
node.nextval = Node(val)

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
node = self.headval
# If list is empty, simply return.
if node == None:
return
# If head node needs to be deleted.
if index == 0:
self.headval = node.nextval
del node
return
# else traverse list upto the correct position.
while index > 1 and node.nextval != None:
node = node.nextval
index -= 1
# If correct position present in list then delete it.
if index == 1 and node.nextval != None:
temp = node.nextval
node.nextval = temp.nextval
del temp

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
index = 0
node = self.headval
while node != None:
if node.dataval == val:
return index
index += 1
node = node.nextval
return False

def reverse(self):
# Fill in this method, which reverses the list
if self.headval == None:
return
# I'm using 3 pointer approach to reverse the list
prev = None
curr = self.headval
Next = curr.nextval
while Next != None:
curr.nextval = prev
prev = curr
curr = Next
Next = curr.nextval
curr.nextval = prev
self.headval = curr

#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 ]")

Screenshot of output:-


Related Solutions

Problem 2: Caesar Cipher Decryption] Write a python method that takes two parameters: A parameter of...
Problem 2: Caesar Cipher Decryption] Write a python method that takes two parameters: A parameter of type str and a parameter of type int. The first parameter is the plaintext message, and the second parameter is the encryption key. The method strictly does the following tasks: a. Reverse the operations performed by the encryption method to obtain the plaintext message. The method’s header is as follows: def casesardecryption(s, key):
C++ language or Python. Linked Lists You are given a linked list that contains N integers....
C++ language or Python. Linked Lists You are given a linked list that contains N integers. You are to perform the following reverse operation on the list: Select all the subparts of the list that contain only even integers. For example, if the list is {1,2,8,9,12,16}, then the selected subparts will be {2,8}, {12,16}. Reverse the selected subpart such as {8,2} and {16,12}. The list should now be {1,8,2,9,16,12}. Your node definition should consist of 2 elements: the integer value...
In python i want to create a function. The function will take in two linked lists...
In python i want to create a function. The function will take in two linked lists as the parameters. If one is shorter than the other then the shorter will be the length. I want to take the values from both linked lists and turn them into tuples. I then want these tuples to be put into a new linked list. I want to return that linked list. I want to do this using recursion and no helper functions or...
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...
Can someone do this python program? Write a function that takes a number as a parameter...
Can someone do this python program? Write a function that takes a number as a parameter and then prints out all of the factors for that number.
In python I want to create a function that takes in a linked list. Using recursion...
In python I want to create a function that takes in a linked list. Using recursion only, I want to check if the linked list is sorted. How do i do this?
USING IDLE PYTHON: A greengrocer would like to maintain a linked lists about his products. For...
USING IDLE PYTHON: A greengrocer would like to maintain a linked lists about his products. For each product he saves it name, price and stock amount. Write a program that creates an empty linked list and then prompts to user to do one of the following: 1. Add a product to the list (anywhere) 2. Print all products in the LinkedList 3. Print all products above a certain price 4. Print all low-stock products ( Less than 20 pounds) 5....
Please include comments on what you are doing.   Using linked lists, write a Python program that...
Please include comments on what you are doing.   Using linked lists, write a Python program that performs the following tasks: store the records for each college found in the input file - colleges.csv - into a linked list. (File includes name and state data fields) allow the user to search the linked list for a college’s name; display a message indicating whether or not the college’s name was in the database allow the user to enter a state's name and...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT