-
Notifications
You must be signed in to change notification settings - Fork 0
/
100-singly_linked_list.py
80 lines (64 loc) · 2.17 KB
/
100-singly_linked_list.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/python3
"""Define classes for a singly-linked list."""
class Node:
"""Represent a node in a singly-linked list v."""
def __init__(self, data, next_node=None):
"""Initialize a new Node.
Args:
data (int): The data of the new Node.
next_node (Node): The next node of the new Node.
"""
self.data = data
self.next_node = next_node
@property
def data(self):
"""Get/set the data of the Node."""
return (self.__data)
@data.setter
def data(self, value):
if not isinstance(value, int):
raise TypeError("data must be an integer")
self.__data = value
@property
def next_node(self):
"""Get/set the next_node of the Node."""
return (self.__next_node)
@next_node.setter
def next_node(self, value):
if not isinstance(value, Node) and value is not None:
raise TypeError("next_node must be a Node object")
self.__next_node = value
class SinglyLinkedList:
"""Represent a singly-linked list."""
def __init__(self):
"""Initalize a new SinglyLinkedList."""
self.__head = None
def sorted_insert(self, value):
"""Insert a new Node to the SinglyLinkedList.
The node is inserted into the list at the correct
ordered numerical position.
Args:
value (Node): The new Node to insert.
"""
new = Node(value)
if self.__head is None:
new.next_node = None
self.__head = new
elif self.__head.data > value:
new.next_node = self.__head
self.__head = new
else:
tmp = self.__head
while (tmp.next_node is not None and
tmp.next_node.data < value):
tmp = tmp.next_node
new.next_node = tmp.next_node
tmp.next_node = new
def __str__(self):
"""Define the print() representation of a SinglyLinkedList."""
values = []
tmp = self.__head
while tmp is not None:
values.append(str(tmp.data))
tmp = tmp.next_node
return ('\n'.join(values))