Create list/node class Python
python
Solution
You need to find the last node without a `.nextEl` pointer and add the node there:
def add(self, newNode):
node = self.firstNode
while node.nextEl is not None:
node = next.nextEl
node.nextEl = newNode
Because this has to traverse the whole list, most linked-list implementations also keep a reference to the last element:
class List(object):
first = last = None
def __init__(self, fnode):
self.add(fnode)
def add(self, newNode):
if self.first is None:
self.first = self.last = newNode
else:
self.last.nextEl = self.last = newNode
Because Python assigns to multiple targets from left to right, `self.last.nextEl` is set to `newNode` before `self.last`.
Some style notes on your code:
- Use `is None` and `is not None` to test if an identifier points to `None` (it's a singleton).
- There is no need for accessors in Python; just refer to the attributes directly.
Unless this is Python 3, use new-style classes by inheriting from `object`:
class Node(object):
# ...
Problem
As exercise, I would like to create my own node/list class. Anyway I don't understand how to add a node to list...here's my code: ``` class Node: def __init__(self, value): self.element = value self.nextEl = None def getEl(self): return self.element def getNext(): return self.nextEl class List: def __init__(self, fnode): self.firstNode = fnode def add(self, newNode): def printList(self): temp = self.firstNode while (temp != None): print temp.element temp = temp.nextEl ```