Need help debugging. For add(item) [aka def add(self, value)], I have the follow
ID: 3736429 • Letter: N
Question
Need help debugging. For add(item) [aka def add(self, value)], I have the following code. When I run the program and call self.head it works; how do I get self.tail to work?
def add(self, value):
#write your code here
temp = Node(value)
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getValue() > value:
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
What I'm getting:
Program:
Framework:
class Node:
def __init__(self, value):
self.value = value
self.next = None
def getValue(self):
return self.value
def getNext(self):
return self.next
def setValue(self,new_value):
self.value = new_value
def setNext(self,new_next):
self.next = new_next
def __str__(self):
return ("{}".format(self.value))
__repr__ = __str__
class OrderedLinkedList:
#Do NOT modify the constructor
def __init__(self):
self.head=None
self.tail=None
self.count=0
def add(self, value):
#Above code goes here
Explanation / Answer
class OrderedLinkedList:
#Do NOT modify the constructor
def __init__(self):
self.head=None
self.tail=None
self.count=0
def add(self, value):
s=self.head
max=0
for i in range(self.count):
if max<s.getValue():
max=s.getValue()
s=s.getNext()
self.tail=max
temp = Node(value)
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getValue() > value:
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
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.