Question: Remove Compartment Sheldon is a train maniac. He loves attaching each compartment of a train to the next with a linking chain as his hobby.
Remove Compartment
Sheldon is a train maniac. He loves attaching each compartment of a train to the next with a linking chain as his hobby. Now he is removing the nth compartment from the end of the train. Can you model the scenario by writing a method that takes the compartment sequence and a number; the method returns the changed or unchanged train compartment sequence.
Constraint:
You cannot create any new linked list. You have to change the given one.
Sample Input
Sample Output
You must Run this cell for your driver code to execute successfully
#Run this cell
class Node:
def initselfelem,next None:
self.elem,self.next elem,next
def createListarr:
head Nodearr
tail head
for i in rangelenarr:
newNode Nodearri
tail.next newNode
tail newNode
return head
def printLinkedListhead:
temp head
while temp None:
if temp.next None:
printtempelem, end
else:
printtempelem
temp temp.next
print
Driver code:
def removecompartmentheadn:
#TO DO
printTest Case
head createListnparray
printOriginal Compartment Sequence: end
printLinkedListhead
head removecompartmenthead
printChanged Compartment Sequence: end
printLinkedListhead #This should print
print
printTest Case
head createListnparray
printOriginal Compartment Sequence: end
printLinkedListhead
head removecompartmenthead
printChanged Compartment Sequence: end
printLinkedListhead #This should print
print
printTest Case
head createListnparray
printOriginal Compartment Sequence: end
printLinkedListhead
head removecompartmenthead
printChanged Compartment Sequence: end
printLinkedListhead #This should print
print
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
