-2
Hello, I need to create a function that receives an unordered list in the structure of nodes and it should reverse the order of the elements of that list, I tried to make a L[::-1]
to reverse the list but it didn’t work, I tried hard and I have no idea how to do it, I would like your help. I already have the classes implemented, follows:
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
def __str__(self):
tmp = self.head
lstr = ''
while tmp != None:
lstr += str(tmp.data) + ' '
tmp = tmp.getNext()
return lstr
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
the function to invert the list looks like this:
def inverterLista(L : UnorderedList):
# solução
return L
Here some tests:
L = UnorderedList()
L.add(1)
L.add(2)
L.add(3)
L.add(4)
L.add(5)
print(f'Lista antes: {L}')
L = inverterLista(L)
print(f'Lista depois: {L}')
I ask for your help, I’m a beginner in python and I haven’t seen anything like this yet, I haven’t found anything about how to do this in python either, so how could I reverse this chained list?
Hello, thank you for the answer, but Sort does not work for this problem see that returned the following error: Attributeerror: 'Unorderedlist' Object has no attribute 'Sort'
– Gabriel
I moved the solution, see if it satisfies what you wanted
– Mac Sabino