-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100-singly_linked_list.py
executable file
·78 lines (63 loc) · 2.36 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
#!/usr/bin/python3
"""This module define classes for singly-linked list impementation"""
class Node:
"""Objs of this clsass represents a node in a singly-linked list."""
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):
"""property(get&set) for 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):
"""property(get&set) for the next_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:
"""This class represents a singly-linked list."""
def __init__(self):
"""Initialize 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 sorted
position in the list (increasing order)
Args:
value (Node): The new Node to insert.
"""
new_node = Node(value)
if self.__head is None:
self.__head = new_node
elif self.__head.data > new_node.data:
new_node.next_node = self.__head
self.__head = new_node
else:
current_node = self.__head
while (current_node.next_node is not None and
current_node.next_node.data < value):
current_node = current_node.next_node
new_node.next_node = current_node.next_node
current_node.next_node = new_node
def __str__(self):
"""The print() representation of a SinglyLinkedList obj"""
node_list = []
current_node = self.__head
while (current_node is not None):
node_list.append(str(current_node.data))
current_node = current_node.next_node
return '\n'.join(node_list)