I
I
igoodmood2016-03-26 12:39:29
Python
igoodmood, 2016-03-26 12:39:29

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

2 answer(s)
A
abcd0x00, 2016-03-26
@igoodmood

>>> 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 
>>>

S
sim3x, 2016-03-26
@sim3x

https://docs.python.org/3/tutorial/datastructures....
Add an item to the end of the list. Equivalent to a[len(a):] = [x].

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question