Question
Python help; Instructions and test cases are posted.
Below is what I have for add(item), but it is returning '8' instead of '58' for ordered_ll.tail.
def add(self, value):
#write your code here
s=self.head
maxVal=0
for i in range(self.count):
if maxVal<s.getValue():
maxVal=s.getValue()
s=s.getNext()
self.tail=maxVal
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
Instructions: In class, we worked on the implementation of a linked list. That data structure keeps the elements of the linked list unsorted. Based on the LinkedList code, implement the data structure OrderedLinkedList with the following characteristics: . OrderedLinkedList) creates a new ordered list that is empty. It needs no parameters and returns nothing. Assume the items in the list are unique . add(item) adds a new Node with value-item to the list making sure that the ascending order . delete(item) removes the Node with value-item from the list. It needs the item and modifies . search(item) searches for the Node with value-item in the list. It needs the item and returns is preserved. It needs the item and returns nothing. [40 pts] the list. You can assume the Node is present in the list. [20 pts] a boolean value. [10 pts] . pop) removes and returns the last Node in the list. It needs nothing and returns an the value of the Node. [20 pts] .isEmpty0 tests to see whether the list is empty. It needs no parameters and returns a boolean value. [5 pts] size) returns the number of items in the list. It needs no parameters and returns an integer [5 pts] * NOTE: There is no partial credit for methods that do not work properly. Code will be tested calling all methods and comparing the final list EXAMPLE >>>ordered 11-OrderedLinkedList () >>> ordered 1 1 add ( 8 ) >>> ordered 11.add (7) >>>ordered 11.add (3) >>>ordered 11.add (-6) >>>ordered 11.add (58) >>>ordered 11.add (33) >>> ordered 11.add (1) >>>ordered 11.add (-88)
Explanation / Answer
try the below code:
i hope this works.
def add(self,item):
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getData() > item:
stop = True
else:
previous = current
current = current.getNext()
temp = Node(item)
if previous == None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)