[Python] Need help debugging. Instructions, my code, and sample cases are below!
ID: 3741281 • Letter: #
Question
[Python] Need help debugging. Instructions, my code, and sample cases are below! I'm having trouble with ordered_ll.tail.
def add(self, item):
#write your code here
temp = Node(item)
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getValue() > item:
stop = True
else:
previous = current
current = current.getNext()
if previous == None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)
self.count+=1
Explanation / Answer
The sample cases that you pasted looked okay. You should paste them as text and not as image.
In add funtion you are not updating the tail. For the first item your head and tail will be changed from None to something and also will be equal and then on it will depend if head/tail changes or not.
If new item smaller than head then only update head, if larger than tail then only update tail and if between head or tail then need not update.
So the change in add funtion code will be
def add(self, item):
#write your code here
temp = Node(item)
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getValue() > item:
stop = True
else:
previous = current
current = current.getNext()
if previous == None:
if stop == False: #Means 1st item, otherwise previous != None or stop != False
self.tail = temp
temp.setNext(self.head)
self.head = temp
else:
if current == None: # Means last element is updated, so make new tail
self.tail = temp
temp.setNext(current)
previous.setNext(temp)
self.count+=1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.