Question: In the file you downloaded ( or opened ) at the beginning of this activity, add the method duplicate ( self , item ) to

In the file you downloaded (or opened) at the beginning of this activity, add the method duplicate(self, item) to the LinkedList class. This method will modify the original list such that if there is a node that has a value that is equal to item, that node will be duplicated (do not duplicate the added nodes). Note that you should be mutating the original link list; so you are not allowed to create new instances of the LinkedList class, you are only allowed to create Nodes and update links. Method returns None. Submit your code in the R6 Recitation Activity before the end of your recitation.
You can test your code with this small doctest:
'''
>>> lst = LinkedList()
>>> lst.add(4)
>>> lst.add(5)
>>> lst.add(6)
>>> lst
Head:Node(6)
Tail:Node(4)
List:6->5->4
>>> lst.duplicate(6)
>>> lst
Head:Node(6)
Tail:Node(4)
List:6->6->5->4
>>> lst.duplicate(13)
>>> lst
Head:Node(6)
Tail:Node(4)
List:6->6->5->4
>>> lst.add(1)
>>> lst.duplicate(6)
>>> lst
Head:Node(1)
Tail:Node(4)
List:1->6->6->6->6->5->4
>>> lst.duplicate(4)
>>> lst
Head:Node(1)
Tail:Node(4)
List:1->6->6->6->6->5->4->4
'''
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return "Node({})".format(self.value)
__repr__=__str__
class LinkedList:
def __init__(self):
self.head=None
self.tail=None
def __str__(self):
temp=self.head
out=[]
while temp:
out.append(str(temp.value))
temp=temp.next
out='->'.join(out)
return 'Head:{}
Tail:{}
List:{}'.format(self.head,self.tail,out)
__repr__=__str__
def isEmpty(self):
return self.head==None
def __len__(self):
current=self.head
count=0
while current is not None:
count +=1
current = current.next
return count
def add(self, value):
newNode=Node(value)
if self.isEmpty():
self.head=newNode
self.tail=newNode
else:
newNode.next=self.head
self.head=newNode
def duplicate(self, item):
# YOUR CODE STARTS HERE
pass

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!