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
10->15->34->41->56->72
2
10->15->34->41->56->72
7
10->15->34->41->56->72
6
Sample Output
10->15->34->41->72
10->15->34->41->56->72
15->34->41->56->72
You must Run this cell for your driver code to execute successfully
#Run this cell
class Node:
def __init__(self,elem,next = None):
self.elem,self.next = elem,next
def createList(arr):
head = Node(arr[0])
tail = head
for i in range(1,len(arr)):
newNode = Node(arr[i])
tail.next = newNode
tail = newNode
return head
def printLinkedList(head):
temp = head
while temp != None:
if temp.next != None:
print(temp.elem, end ='-->')
else:
print(temp.elem)
temp = temp.next
print()
Driver code:
def remove_compartment(head,n):
#TO DO
print('==============Test Case 1=============')
head = createList(np.array([10,15,34,41,56,72]))
print('Original Compartment Sequence: ', end ='')
printLinkedList(head)
head = remove_compartment(head,2)
print('Changed Compartment Sequence: ', end ='')
printLinkedList(head) #This should print 10-->15-->34-->41-->72
print()
print('==============Test Case 2=============')
head = createList(np.array([10,15,34,41,56,72]))
print('Original Compartment Sequence: ', end ='')
printLinkedList(head)
head = remove_compartment(head,7)
print('Changed Compartment Sequence: ', end ='')
printLinkedList(head) #This should print 10-->15-->34-->41-->56-->72
print()
print('==============Test Case 3=============')
head = createList(np.array([10,15,34,41,56,72]))
print('Original Compartment Sequence: ', end ='')
printLinkedList(head)
head = remove_compartment(head,6)
print('Changed Compartment Sequence: ', end ='')
printLinkedList(head) #This should print 15-->34-->41-->56-->72
print()

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!