Answer the question
In order to leave comments, you need to log in
How to implement a function to add an element to the end of the list?
I want to create a function to add an element to the end of a list. But I don't quite understand the implementation.
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
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 append(self,item):
while current != None:
temp = Node(item,current.getNext())
temp.setNext(self.head) # На этом моменте ход мыслей пропадает
Answer the question
In order to leave comments, you need to log in
>>> class UnorderedList:
... def __init__(self):
... self.head = None
...
... def append(self, item):
... newnode = Node(item)
... if self.head is None:
... self.head = newnode
... return
... current = self.head
... while True:
... nextnode = current.getNext()
... if nextnode is None:
... break
... current = nextnode
... current.setNext(newnode)
...
... def print(self):
... current = self.head
... while current is not None:
... print(current.getData(), end=' ')
... current = current.getNext()
... print()
...
>>> class Node:
... def __init__(self, data):
... self.data = data
... self.next = None
...
... def getData(self):
... return self.data
...
... def getNext(self):
... return self.next
...
... def setData(self, data):
... self.data = data
...
... def setNext(self, node):
... self.next = node
...
>>> lst = UnorderedList()
>>> lst.append(1)
>>> lst.append(2)
>>> lst.append(3)
>>> lst.print()
1 2 3
>>>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question