-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNode.py
More file actions
54 lines (46 loc) · 1.54 KB
/
Copy pathNode.py
File metadata and controls
54 lines (46 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
node.py
author: James heliotis
description: A linkable node class for use in stacks, queues, and linked lists
"""
class Node:
__slots__ = "value", "link"
def __init__( self, value, link = None ):
""" Create a new node and optionally link it to an existing one.
param value: the value to be stored in the new node
param link: the node linked to this one
"""
self.value = value
self.link = link
def __str__( self ):
""" Return a string representation of the contents of
this node. The link is not included.
"""
return str( self.value )
def __repr__( self ):
""" Return a string that, if evaluated, would recreate
this node and the node to which it is linked.
This function should not be called for a circular
list.
"""
return "Node(" + repr( self.value ) + "," + \
repr( self.link ) + ")"
def size_to_end( node ):
""" Count how many nodes from this one to a node whose link is None.
return: the length of the list starting at node
"""
if node == None:
return 0
else:
return 1 + size_to_end( node.link )
def test():
nodes = Node( 1, Node( "two", Node( 3.0 ) ) )
n = nodes
while n != None:
print( n.value )
n = n.link
print( "\n" + str( size_to_end( nodes ) ) + " nodes.\n" )
print( nodes )
print( repr( nodes ) )
if __name__ == "__main__":
test()