Question
The following Node class can be used to construct chain of nodes: class Node: def __init__(self, init_data): self.data = init_data self.next = None def get_data(self):
The following Node class can be used to construct chain of nodes:
class Node: def __init__(self, init_data): self.data = init_data self.next = None def get_data(self): return self.data def get_next(self): return self.next def set_data(self, new_data): self.data = new_data def set_next(self, new_next): self.next = new_next def __str__(self): return str(self.data)
Write the zero_between() function which takes three parameters: a reference to the first node in a chain of nodes, an integer value1, and an integer value2. The function should set all of the data values in the chain that lie between the two values (value1 and value2) to zero. The function returns an integer: number of data values in the chain which were set to zero. For example, consider the following chain of nodes:
if we called the function as follows:
changes = zero_between(x, 11, 14)
the resulting chain would be the following (where all data values between 11 and 14 have been set to 0):
The function returns 2 (as two data values were set to 0). You can assume all values in the list are unique (i.e. there are no repeated values in the list).
For there to be any changes, the first value (value1) must appear in the chain before the second value (value2). If either value1 or value2 do not appear in the chain, or if value1 appears after value2), then the function should return -1 and no changes should be made to the chain. If the chain is empty, the function returns -1. If value1 is equal to value2, the function returns -1. If there are no nodes in the chain that lie between value1 and value2 (i.e. they are adjacent in the chain), then your function should return 0 (as no data values are change).
Note: You may assume that the Node class is defined and you should not include this class in your answer.
For example:
Test | Result |
---|---|
x = Node(10) b = Node(11) c = Node(12) d = Node(13) e = Node(14) x.set_next(b) b.set_next(c) c.set_next(d) d.set_next(e) changes = zero_between(x, 11, 14) current = x while current != None: print(current, end = ' ') current = current.get_next() print('(' + str(changes) + ')') | 10 11 0 0 14 (2) |
a = Node(1) b = Node(2) c = Node(3) d = Node(4) e = Node(5) f = Node(6) a.set_next(b) b.set_next(c) c.set_next(d) d.set_next(e) e.set_next(f) changes = zero_between(a, 5, 2) current = a while current != None: print(current, end = ' ') current = current.get_next() print('(' + str(changes) + ')') | 1 2 3 4 5 6 (-1) |
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started