Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Question 4: Extend the UnorderedList class by adding the insert(self, index, ite

ID: 3838513 • Letter: Q

Question

Question 4:
Extend the UnorderedList class by adding the insert(self, index, item) method that that takes an integer index as a parameter and inserts the new item at the index position in the unordered linked list. The index should be in the range [0..length-1].

The implementations of the Node and LinkedListIterator are provided to you as part of this exercise. You can simply use: Node(), get_next(), as well as get_data() as necessary in your function definition.
===========================================================
For example:
===========================================================
Test:
my_list = UnorderedList()
for x in [3,5,4,6,7,8]:
my_list.add(x)
my_list.insert(0, 9)
for num in my_list:
print(num, end=" ")
print()
===========================================================
Result:
9 8 7 6 4 5 3
===========================================================

Explanation / Answer

Not much information was provided regarding language to be used. As declaration seems of insert(self, index, item) I have used python language as it seems most appropiate as it was in declaration.

class UnorderedList(object):
list_object = []
def Node(self):
"""
First Element in the list to be stored
"""
item = str(raw_input("Enter an element: "))
self.list_object.append(item)
def insert(self,index,item):
"""
Insert element at specified location
"""
if index > len(self.list_object):
print("Please provide correct index")
else:
self.list_object.insert(index, item)
def add(self, item):
"""
Append element by adding to list
"""
self.list_object.append(item)
def get_next(self, item):
"""
get next element of list if provided an element to be searched
"""
flag = 0
for i in range(0,len(self.list_object)):
if self.list_object[i] == item:
flag = 1
if i == len(self.list_object)-1:
print "It is last element"
else:
print self.list_object[i+1]
if flag == 0:
print "Element not found"
  
def get_data(self):
"""
Print all data in list
"""
str_data = ""
for i in self.list_object:
str_data += str(i) +" "
print str_data

k = UnorderedList()
k.Node()
for x in [2,3,45,6,8]:
k.add(x)
k.insert(1,2)
k.insert(2,3)
k.insert(3,4)
k.get_data()
k.get_next(8)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote