node class python

Solutions on MaxInterview for node class python by the best coders in the world

showing results for - "node class python"
Bianca
01 Jul 2017
1class Node(object):
2 
3    def __init__(self, data=None, next_node=None):
4        self.data = data
5        self.next_node = next_node
6
Amelie
02 Nov 2018
1You need to find the last node without a .nextEl pointer and add the node there:
2
3def add(self, newNode):
4    node = self.firstNode
5    while node.nextEl is not None:
6        node = next.nextEl
7    node.nextEl = newNode
8Because this has to traverse the whole list, most linked-list implementations also keep a reference to the last element:
9
10class List(object):
11    first = last = None
12
13    def __init__(self, fnode):
14        self.add(fnode)
15
16    def add(self, newNode):
17        if self.first is None:
18            self.first = self.last = newNode
19        else:
20            self.last.nextEl = self.last = newNode
21Because Python assigns to multiple targets from left to right, self.last.nextEl is set to newNode before self.last.
22
23Some style notes on your code:
24
25Use is None and is not None to test if an identifier points to None (it's a singleton).
26There is no need for accessors in Python; just refer to the attributes directly.
27Unless this is Python 3, use new-style classes by inheriting from object:
28
29class Node(object):
30    # ...